Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 46 ยท Data, Networking and Persistence

Codable and JSON in iOS Apps

Decode JSON into Swift models with Decodable: CodingKeys, snake_case, dates, optional fields, nested data and readable decoding errors, with runnable examples.

Almost every app talks to a server, and servers speak JSON. Swift turns JSON into typed values with the Codable family of protocols. Once a response is decoded into a struct, the rest of your app works with safe, named properties instead of loose dictionaries, and SwiftUI views can display those structs directly.

The Swift track already introduced the basics in Codable Basics. This lesson focuses on what matters in an iOS app: matching real server JSON that rarely looks like your ideal model, handling dates and missing fields, and reading decoding errors so you can fix a broken payload quickly. Everything here runs on the site, because JSONDecoder is part of Foundation.

Decodable, Encodable and Codable

Decodable converts data into your type. Encodable converts your type into data. Codable is just Decodable & Encodable. An app that only reads from an API needs Decodable alone, and it is good practice to ask for no more than you use.

When all stored properties are themselves decodable (String, Int, Double, Bool, Date, URL, arrays, optionals, other decodable types), the compiler writes the conformance for you.

Swift Decoding a simple model

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Notice that the integer 12 decodes into a Double without trouble, but a JSON string "12" would not. Decoding is strict about types.

Renaming keys: snake_case and CodingKeys

Many APIs use snake_case while Swift uses camelCase. There are two tools.

The first is a decoder-wide strategy that converts keys automatically:

Swift
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase

With it, in_stock fills inStock. This works when the names differ only by case style.

The second is a CodingKeys enum, which maps individual names. Use it when the server's names are different words, abbreviated, or inconsistent:

Swift CodingKeys and snake_case

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Once you add a CodingKeys enum, it must list every property you want decoded. A property left out is skipped, so it needs a default value or must be computed. Pick one approach per type: mixing CodingKeys with .convertFromSnakeCase is confusing, because the strategy runs first and your raw values then need to match the converted names.

Optional, missing and null fields

Real JSON changes over time. Fields appear, vanish or are null. Mark a property optional when the server may omit it or send null:

Swift
struct Review: Decodable {
    let rating: Int
    let comment: String?      // missing or null is fine
}

An optional property decodes to nil for both a missing key and an explicit null. A non-optional property with a missing key throws an error and the whole decode fails. Be deliberate: if a field is truly required by your UI, keep it non-optional so a broken payload is caught early at the boundary instead of showing blank screens later.

When you want a default instead of nil, write a custom init(from:):

Swift Defaults for missing fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

decodeIfPresent returns nil when the key is missing or null, and then ?? supplies the default.

Dates

JSON has no date type. Servers send dates as strings (ISO 8601 such as 2026-03-14T09:30:00Z) or numbers (seconds since 1970). Tell the decoder which format to expect with dateDecodingStrategy:

Swift Decoding dates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The .iso8601 strategy does not accept fractional seconds such as 09:30:00.123Z. If your server sends them, use a custom strategy with ISO8601DateFormatter and .withFractionalSeconds, or .custom for several formats. A Date is a point in time and has no time zone. Convert it for display with a Date.FormatStyle or DateFormatter in the user's locale, never in the model.

Nested JSON

Real responses are nested: an object that holds an array of objects, wrapped in an envelope with metadata. Model the shape you receive with nested types, and flatten later in a view model if your UI wants something simpler.

Swift Envelope, arrays and nested objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Identifiable here lets SwiftUI's List and ForEach use the decoded days directly, as described in List, ForEach and Identifiable. The id is a computed property, so it is not part of the JSON.

Reading decoding errors

Decoding throws a DecodingError with four cases that tell you precisely what went wrong:

  • keyNotFound: a required key is missing.
  • typeMismatch: the value has another type than expected, for example a string where a number was expected.
  • valueNotFound: the value was null for a non-optional property.
  • dataCorrupted: the data is not valid JSON, or a custom conversion (such as a date) failed.

Each case carries a coding path, which is the trail of keys and array indexes leading to the problem. Printing it saves hours of guessing.

Swift Making decoding errors readable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

In production code, log these details for developers, but show users a calm message such as "We couldn't load this right now". The next lesson puts decoding behind a network call and a loading state.

Practical advice

  • Keep wire models and UI models apart when they differ. Decode what the server sends. Convert to a view-friendly type if needed, so a server change touches one place.
  • Use one configured decoder. Create it once (with date and key strategies) instead of repeating settings.
  • Prefer let and value types. Structs make models easy to test and safe to share between tasks.
  • Decode on the right side of the boundary. Decode fully before handing data to the UI. Views should never see raw JSON.
  • Be careful with enums. An unknown string for an enum property throws. Add a fallback case with a custom initializer when the server may add values.
  • Large payloads: decoding is quick for typical responses. For very large files, decode off the main thread (see the concurrency lessons).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A server sends {"user_name": "Mira"} and your struct has a property userName. What is the simplest way to decode it?

    The decoder's snake case strategy converts user_name to userName automatically. A CodingKeys enum also works, especially when names differ by more than case style.
  2. 2. What happens when a non-optional property has no matching key in the JSON?

    A missing required key makes the whole decode fail. Make the property optional or provide a default in a custom initializer if the field may be absent.
  3. 3. Which decoder setting handles dates like 2026-03-14T09:30:00Z?

    Dates need a dateDecodingStrategy. Without it, the default expects a number of seconds since 2001, so a string fails.
  4. 4. What is the coding path in a DecodingError useful for?

    The coding path is the trail of keys and indexes to the bad value, such as [1].title, which pinpoints the problem in a big payload.
  5. 5. When should you declare a property optional?

    Optionals express real absence. Overusing them pushes nil checks into the UI, while required fields should fail early at the boundary.

Summary

  • Decodable turns JSON into your types; the compiler synthesizes it when all properties are decodable.
  • Use .convertFromSnakeCase for case-style differences and CodingKeys for individual renames.
  • Optional properties accept missing keys and null; decodeIfPresent with ?? supplies defaults.
  • Choose a dateDecodingStrategy that matches the server (.iso8601, .secondsSince1970 or custom).
  • Model nested and enveloped JSON with nested types.
  • Read DecodingError cases and the coding path to fix payload problems quickly.

Next: Networking with URLSession and async/await