Swift. JSON serialization/deserialization
Working with JSON format, probably one of the most common task in the software development, whether you organizing the data storage or send data over network or any other reason. Therefore it will be very common task in the mobile development. Likely, Swift provides build in functionality to work with JSON format.
To encode (serialize) or decode (deserialize) our object to JSON format we need to make sure that object implements Encodable
protocol and/or Decodable
protocol. Or simply it can implement Codable
protocol that combines both Encodable
and Decodable
protocols.
Something like this:
struct Employee: Codable {
var id: UUID
var firstName: String
var lastName: String
}
Because, most likely we are going to need serialize different object in different places, it won’t be a bad idea to create some sort of helper class that encapsulates encoding/decoding logic.
import Foundation
struct JsonHelper { }
Serialization
Lets serialize our object first. To serialize (encode) object we need to use JSONEncoder
.
static func toJson<T: Encodable>(_ data: T, encoding: String.Encoding = .utf8) -> String {
do {
let encodedData = try JSONEncoder().encode(data)
let jsonString = String(data: encodedData, encoding: encoding)
return jsonString ?? ""
}
catch {
return ""
}
}
NOTE: pay attention to what character encoding type you are using for serialization, because you are going to need to use the same type for deserialization.
Deserialization
When we have JSON formatted string we need to deserialize it. To deserialize (decode) object we need to use JSONDecoder
.
static func fromJson<T: Decodable>(_ data: String?, encoding: String.Encoding = .utf8) -> T? {
do {
if data != nil, let dataFromJsonString = data!.data(using: encoding) {
return try JSONDecoder().decode(T.self, from: dataFromJsonString)
}
return nil
}
catch {
return nil
}
}
NOTE: do not forget about character encoding.
Usage
Now, when we have everything we need we can try to use it.
var employee = Employee(id: UUID(), firstName: "John", lastName: "Doe")
let json = JsonHelper.toJson(employee)
employee = JsonHelper.fromJson(json)!
Summary
One more thing is left. Lets combine all together.
import Foundation
struct JsonHelper {
static func toJson<T: Encodable>(_ data: T, encoding: String.Encoding = .utf8) -> String {
do {
let encodedData = try JSONEncoder().encode(data)
let jsonString = String(data: encodedData, encoding: encoding)
return jsonString ?? ""
}
catch {
return ""
}
}
static func fromJson<T: Decodable>(_ data: String?, encoding: String.Encoding = .utf8) -> T? {
do {
if data != nil, let dataFromJsonString = data!.data(using: encoding) {
return try JSONDecoder().decode(T.self, from: dataFromJsonString)
}
return nil
}
catch {
return nil
}
}
}
Source Code
The sample application for this article you can find here .