what is it
- Allows creation of Swift object directly from JSON and vice versa
- Introduced in Swift 4.0
How to use:
- Derive your class/struct from Codeable
struct Student : Codable {
var name : String
var roll_no: String
var class : String
}
- Creating swift object from JSON string
let jsonData = jsonString.data(using: .utf8)
let student = try JSONDecoder().decoder (Student.self, from jsonData)
print (student.name)
- use CodingKey when the Json variable is different from struct variable name
struct Student : Codable {
var name : String
var rollNo: String
var class : String
enum CodingKeys: String, CodingKey {
case name = “student_name”
case rollNo = “roll_no”
case class
}
}
- Encoding is equally straight forward
let jsonData = try! JSONEncoder().encode(student)
let jsonString = String(data: jsonData, encoding: .utf8)!
- Working with array of objects
let students = try! JSONDecoder().decode([Student].self, from: jsonData)
- Working with nested objects
Its just the same, as with simple objects, define nested struct and ensure using top level struct (which also should be a Codeable) to encode/decode