Automatic JSON serialization and deserialization of objects in Swift

前端 未结 7 2062
走了就别回头了
走了就别回头了 2020-12-13 00:21

I\'m looking for a way to automatically serialize and deserialize class instances in Swift. Let\'s assume we have defined the following class …

class Person          


        
7条回答
  •  清歌不尽
    2020-12-13 00:38

    With Swift 4, you simply have to make your class conform to Codable (Encodable and Decodable protocols) in order to be able to perform JSON serialization and deserialization.

    import Foundation
    
    class Person: Codable {
        let firstName: String
        let lastName: String
    
        init(firstName: String, lastName: String) {
            self.firstName = firstName
            self.lastName = lastName
        }
    }
    

    Usage #1 (encode a Person instance into a JSON string):

    let person = Person(firstName: "John", lastName: "Doe")
    let encoder = JSONEncoder()
    encoder.outputFormatting = .prettyPrinted // if necessary
    let data = try! encoder.encode(person)
    let jsonString = String(data: data, encoding: .utf8)!
    print(jsonString)
    
    /*
     prints:
     {
       "firstName" : "John",
       "lastName" : "Doe"
     }
     */
    

    Usage #2 (decode a JSON string into a Person instance):

    let jsonString = """
    {
      "firstName" : "John",
      "lastName" : "Doe"
    }
    """
    
    let jsonData = jsonString.data(using: .utf8)!
    let decoder = JSONDecoder()
    let person = try! decoder.decode(Person.self, from: jsonData)
    dump(person)
    
    /*
     prints:
     ▿ __lldb_expr_609.Person #0
       - firstName: "John"
       - lastName: "Doe"
     */
    

提交回复
热议问题