Swift/Object Serialization and Deserialization: Difference between revisions

From Chorke Wiki
Jump to navigation Jump to search
 
(One intermediate revision by the same user not shown)
Line 90: Line 90:
}
}
</source>
</source>
==References==
* [https://stackoverflow.com/questions/46537790 Swift Date JSON Decoding for ISO8601]
* [[Swift]]

Latest revision as of 20:52, 1 December 2019

Structure

struct Patient: Codable {
    let id: String
    let mobile: String
    let nameLocal: String
    let nameEnglish: String
    let dateOfBirth: String
}

struct Response: Codable {
    let code: Bool
    let data: Patient
}

// object deserialisation 
var json = """
{
    "code": true,
    "data": {
        "id": "9999",
        "mobile": "01117606778",
        "nameLocal": "Chorke Academia, Inc",
        "nameEnglish": "Chorke Academia, Inc",
        "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)
}

References