Codable in Swift4
Swift4 introduces Codable protocol which makes too simplify to encode and decode to JSON.
This is simple example. Conform to Codable is the only thing that we need to do. We can encode and decode Using JSONEncoder and JSONDecoder.
struct User: Codable {
let id : String
let name : String
}
let user = User(id: "id", name: "name")
let data = "{\"id\":\"id\",\"name\":\"name\"}".data(using: .utf8)!
let encodedData = try? JSONEncoder().encode(user)
let decodedData = try? JSONDecoder().decode(User.self, from: data)CodingKeys can designate JSON key mapping to property. It useful when these are different. This example maps JSON key website-url to property websiteUrl.
struct User: Codable {
let id : String
let name : String
let websiteUrl : String
enum CodingKeys: String, CodingKey {
case id
case name
case websiteUrl = "website_url"
}
}
let user = User(id: "id", name: "name", websiteUrl: "websiteUrl")
let data = "{\"id\":\"id\",\"name\":\"name\", \"website_url\":\"websiteUrl\"}".data(using: .utf8)!
let encodedData = try? JSONEncoder().encode(user)
let decodedData = try? JSONDecoder().decode(User.self, from: data)