Swift/Object Serialization and Deserialization
Structure
struct Patient: Codable {
let id: String
let nameLocal: String
let nameEnglish: String
let mobile: String
let dateOfBirth: String
}
struct Response: Codable {
let code: Bool
let data: Patient
}
// object deserialisation
var json = """
{
"code": true,
"data": {
"id": "9999",
"nameLocal": "Chorke Academia, Inc",
"nameEnglish": "Chorke Academia, Inc",
"mobile": "01117606778",
"dateOfBirth": "2013-01-01 00:00:00"
}
}
"""
var data = Data(json.utf8)
do {
let response = try JSONDecoder().decode(Response.self, from: data)
print(response)
print(response.data)
} catch {
print("Error: \(error)")
}
// array deserialisation
json = """
[{
"name": "Taylor Swift",
"age" : 26
},
{
"name": "Justin Bieber",
"age" : 25
}]
"""
data = Data(json.utf8)
struct Person: Codable {
var name: String
var age: Int
}
do {
let people = try JSONDecoder().decode([Person].self, from: data)
print(people)
} catch {
print(error.localizedDescription)
}
Class
class Person: Codable {
let firstName: String
let lastName: String
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
}
let person = Person(firstName: "John", lastName: "Doe")
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
do {
let data = try encoder.encode(person)
let json = String(data: data, encoding: .utf8)!
print(json)
let people = try JSONDecoder().decode(Person.self, from: json.data(using:.utf8)!)
dump(people)
} catch {
print(error.localizedDescription)
}