← All daysDay 28 of 49 · Part 8: Data, persistence, and networking
Day 28

Codable and JSON

These are the lesson notes for this day. Its build-along tutorial and flash cards have not been written yet.

Lesson 32

Codable and JSON

A type that conforms to Codable can be converted to and from JSON by JSONEncoder and JSONDecoder. For most structs the compiler writes the conversion for you. Use a CodingKeys enum to map names in the JSON to your property names, optionals for fields that may be missing, and a custom init(from:) when the shape of the JSON does not match your model. Options on the decoder handle date formats and naming styles.

One trap is worth remembering. The .convertFromSnakeCase option turns image_url into imageUrl, not imageURL, and a property named imageURL then quietly fails to decode. When decoding does fail, read the DecodingError: it names the exact key and the path to it.

Exercise

Decode real JSON from a public API into structs. Make one field optional, and rename one with CodingKeys. Then break the JSON on purpose and read the error that results.

After this lesson you should be able to answer
  1. What does the compiler generate when you declare a struct Codable?
  2. How do you map a JSON key price_cents to a property named priceCents?
  3. What does a DecodingError tell you?
Resources