Swift/Object Serialization and Deserialization: Difference between revisions

From Chorke Wiki
Jump to navigation Jump to search
(Created page with "==Structure== <source lang="swift"> struct Patient: Codable { let id: String let nameLocal: String let nameEnglish: String let mobile: String let dateOfBir...")
 
Line 3: Line 3:
struct Patient: Codable {
struct Patient: Codable {
     let id: String
     let id: String
    let mobile: String
     let nameLocal: String
     let nameLocal: String
     let nameEnglish: String
     let nameEnglish: String
    let mobile: String
     let dateOfBirth: String
     let dateOfBirth: String
}
}
Line 20: Line 20:
     "data": {
     "data": {
         "id": "9999",
         "id": "9999",
        "mobile": "01117606778",
         "nameLocal": "Chorke Academia, Inc",
         "nameLocal": "Chorke Academia, Inc",
         "nameEnglish": "Chorke Academia, Inc",
         "nameEnglish": "Chorke Academia, Inc",
        "mobile": "01117606778",
         "dateOfBirth": "2013-01-01 00:00:00"
         "dateOfBirth": "2013-01-01 00:00:00"
     }
     }
Line 62: Line 62:
}
}
</source>
</source>


==Class==
==Class==

Revision as of 05:01, 16 April 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)
}