Convert JSON to Swift Objects

January 11, 2019

Parsing JSON in swift has always been a nightmare having to deal with Dictionaries and pulling keys from that dictionary. Swift 4+ makes it easier by having the codable/decodable protocol for JSON deserialization.

Example JSON:

{
    "firstName": "Alex",
    "lastName": "Nguyen",
    "age": 10,
    "gender": "MALE"
}

Swift Models:

Gender.swift

enum BeerStyle : String {
    case male
    case female
}

Person.swift

struct Person: Codable {
    let firstName: String // Required - If not present, serialization will fail
    let middleName: String? // Optional parameter
    let lastName: String
    let age: Int
    let gender: Gender

    // Custom coding keys
    enum CodingKeys : String, CodingKey {
	case firstName
	case middleName = "nickname" //Rename parameter
	case lastName
	case age
        case gender
    }
}

Deserialize

   let data = myJsonString.data(using: utf8)
   let person: Person = JSONDecoder().decode(Person.self, from: data)