DAY #31

Codable (Part 1 of 4)

Data coming from (or going to) an API is not always organized/standardized. For instance, the json keys could have different naming schemes. Consider the case below:

1
2
3
4
5
{
    first_name: ""
    MiddleName: "",
    lastName: "",
}

So how does this get coded? By using a feature called codingkeys. Simply create an enum inside the object you are decoding to as following:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
struct Name: Codable {
  let firstName: String
  let middleName: String
  let lastName: String
  enum CodingKeys: String, CodingKey {
    case firstName = "first_name"
    case middleName = "MiddleName"
    case lastName = "lastName"
  }
}

This codingkeys enum will allow the codable object to map to the json keys.

Originally published 09/16/2021 @ https://pittcsc.org/ Discord

Published here on 09/09/2022. Blog published date reflects the original date of publication.