Automatic JSON serialization and deserialization of objects in Swift

As shown in WWDC2017 @ 24:48 (Swift 4), we will be able to use the Codable protocol. Example

public struct Person : Codable {
   public let firstName:String
   public let lastName:String
   public let location:Location
}

To serialize

let payload: Data = try JSONEncoder().encode(person)

To deserialize

let anotherPerson = try JSONDecoder().decode(Person.self, from: payload)

Note that all properties must conform to the Codable protocol.

An alternative can be JSONCodable which is used by Swagger’s code generator.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)