Codable & JSON

June 02, 2026 1 min read

Codable lets Swift encode/decode JSON into your structs with almost no code.

A decodable model

struct Product: Codable {
    let id: Int
    let title: String
    let price: Double
}

let product = try JSONDecoder().decode(Product.self, from: data)

Mismatched key names

struct User: Codable {
    let firstName: String
    enum CodingKeys: String, CodingKey {
        case firstName = "first_name"  // map snake_case JSON
    }
}
Tip: Set decoder.keyDecodingStrategy = .convertFromSnakeCase to auto-map snake_case keys without CodingKeys.

Summary

Conform your models to Codable and JSONDecoder does the parsing. Use CodingKeys for non-matching JSON keys.