TExcelTAD
Home › Swift › Codable & JSON

Swift Codable & JSON

Almost every app talks JSON: REST APIs, config files, saved settings. Swift makes converting between JSON and your own types almost effortless with the Codable protocol and Foundation's JSONEncoder and JSONDecoder.

What is Codable?

Codable is a type alias for two protocols:

Protocol Direction Used by
Encodable Swift value → JSON (or other format) JSONEncoder
Decodable JSON → Swift value JSONDecoder
Codable both both

If every stored property of a struct is itself Codable (String, Int, Double, Bool, arrays, dictionaries, optionals, other Codable types…), the compiler writes the conversion code for you. You just add : Codable.

Encoding: Swift → JSON

swift · try it yourself
import Foundation

struct Book: Codable {
    let title: String
    let pages: Int
    let tags: [String]
}

let book = Book(title: "Swift Basics", pages: 240, tags: ["ios", "beginner"])

let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]

let data = try encoder.encode(book)
print(String(data: data, encoding: .utf8)!)
{
  "pages" : 240,
  "tags" : [
    "ios",
    "beginner"
  ],
  "title" : "Swift Basics"
}

encode returns raw bytes (Data); we turn them into a String to print them. .sortedKeys makes the key order predictable, which is handy for tests and diffs.

Note: encode and decode are throwing functions, so they need try. In a real app wrap them in do/catch.

Decoding: JSON → Swift

Decoding is the reverse. Tell the decoder which type you expect with Type.self:

swift · try it yourself
import Foundation

struct Weather: Codable {
    let city: String
    let temperature: Double
    let sunny: Bool
}

let json = """
{ "city": "Lisbon", "temperature": 23.5, "sunny": true }
"""

let weather = try JSONDecoder().decode(Weather.self, from: Data(json.utf8))
print("\(weather.city): \(weather.temperature)°C, sunny: \(weather.sunny)")
Lisbon: 23.5°C, sunny: true

Arrays work the same way — decode [Weather].self to get an array back.

Custom key names with CodingKeys

APIs often use snake_case names that don't fit Swift style. Add a nested CodingKeys enum to map JSON keys to property names:

swift · try it yourself
import Foundation

struct User: Codable {
    let id: Int
    let fullName: String
    let isAdmin: Bool

    enum CodingKeys: String, CodingKey {
        case id
        case fullName = "full_name"
        case isAdmin = "is_admin"
    }
}

let json = """
[
  { "id": 1, "full_name": "Grace Hopper", "is_admin": true },
  { "id": 2, "full_name": "Alan Turing", "is_admin": false }
]
"""

let users = try JSONDecoder().decode([User].self, from: Data(json.utf8))
for user in users {
    print(user.id, user.fullName, user.isAdmin ? "(admin)" : "")
}
1 Grace Hopper (admin)
2 Alan Turing 

Tip: If all keys are snake_case, skip CodingKeys and set decoder.keyDecodingStrategy = .convertFromSnakeCase instead.

Optional fields and errors

Make a property optional when the JSON might not contain it — a missing key then decodes as nil. If a required key is missing or has the wrong type, decoding throws a DecodingError that tells you exactly what went wrong:

swift · try it yourself
import Foundation

struct Product: Codable {
    let name: String
    let price: Double
    let discount: Double?
}

let inputs = [
    #"{"name": "Mug", "price": 9.5}"#,
    #"{"name": "Lamp", "price": 30, "discount": 0.2}"#,
    #"{"name": "Desk"}"#,
]

for text in inputs {
    do {
        let p = try JSONDecoder().decode(Product.self, from: Data(text.utf8))
        print(p.name, p.price, p.discount ?? 0)
    } catch DecodingError.keyNotFound(let key, _) {
        print("Missing key:", key.stringValue)
    } catch {
        print("Other error:", error)
    }
}
Mug 9.5 0.0
Lamp 30.0 0.2
Missing key: price

The #"…"# raw strings let us write JSON quotes without escaping them.

Nested types and enums

Codable composes: a struct containing other Codable structs, arrays and enums with raw values works automatically.

swift · try it yourself
import Foundation

enum Priority: String, Codable {
    case low, high
}

struct TodoItem: Codable {
    let title: String
    let priority: Priority
}

struct Project: Codable {
    let name: String
    let tasks: [TodoItem]
}

let project = Project(name: "Launch", tasks: [
    TodoItem(title: "Write docs", priority: .low),
    TodoItem(title: "Fix crash", priority: .high),
])

let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
let data = try encoder.encode(project)
print(String(data: data, encoding: .utf8)!)

let copy = try JSONDecoder().decode(Project.self, from: data)
print(copy.tasks.map(\.priority.rawValue))
{"name":"Launch","tasks":[{"priority":"low","title":"Write docs"},{"priority":"high","title":"Fix crash"}]}
["low", "high"]

A round trip (encode then decode) gives you back an equal value — a useful pattern for saving data to disk.

Test yourself

Which protocol do you adopt to both encode and decode a type?

  1. Encodable
  2. Decodable
  3. Codable
  4. JSONSerializable

What happens when a JSON key is missing for a property declared as let discount: Double??

  1. Decoding throws
  2. The property becomes 0
  3. The property becomes nil
  4. The program crashes

What is a CodingKeys enum used for?

  1. Encrypting JSON
  2. Mapping JSON key names to Swift property names
  3. Sorting the output keys
  4. Declaring which types are Codable