JSON to Swift Codable converter

Paste JSON and get Swift Codable structs. Keys that are missing or null in any array item become optionals, CodingKeys map snake_case names (or use keyDecodingStrategy), and the output ends with a JSONDecoder example including the date strategy.

Updated

Nested structs are named from their keys: orders becomes Order.

The strategy replaces CodingKeys for plain snake_case keys; only odd keys still need a CodingKeys case.

Applies only when every value of that key looks like 2026-03-14T09:30:00Z. Needs a dateDecodingStrategy, shown below.

Swift structs

3 structs, 14 properties

Codable, CodingKeys

Swift Codable structs

import Foundation

struct User: Codable {
    let id: Int
    let firstName: String
    let isActive: Bool
    let balance: Double
    let createdAt: Date
    let address: Address
    let tags: [String]
    let orders: [Order]

    enum CodingKeys: String, CodingKey {
        case id
        case firstName = "first_name"
        case isActive = "is_active"
        case balance
        case createdAt = "created_at"
        case address
        case tags
        case orders
    }
}

struct Address: Codable {
    let city: String
    let pinCode: String

    enum CodingKeys: String, CodingKey {
        case city
        case pinCode = "pin_code"
    }
}

struct Order: Codable {
    let orderId: Int
    let total: Double
    let coupon: String?
    let note: String?

    enum CodingKeys: String, CodingKey {
        case orderId = "order_id"
        case total
        case coupon
        case note
    }
}

// Usage:
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let value = try decoder.decode(User.self, from: data)   // data: Data from URLSession
  • The explicit CodingKeys keep every key exactly as the server sends it. Don't also set keyDecodingStrategy to convertFromSnakeCase on the same decoder: it would convert the keys first and then fail to match these raw values.
  • Date properties need a dateDecodingStrategy. The default, .deferredToDate, expects a number (seconds since 2001-01-01 UTC) and fails on a string like 2026-03-14T09:30:00Z.
  • Optional properties (2) decode a missing key and an explicit null to nil. A non-optional property with a missing key throws keyNotFound.

How are Swift Codable structs worked out from JSON?

Each JSON object becomes a struct that conforms to Codable, so the compiler writes init(from:) and encode(to:) for you. A list becomes [T], with T taken from all the items together. A key that is missing from some items, or null in some, becomes an Optional (String?), which Swift's synthesized decoder reads with decodeIfPresent: a missing key and an explicit null both give nil. A non-optional property with a missing key throws DecodingError.keyNotFound.

Swift has one Int (64-bit on every current Apple platform) and one Double, so unlike Kotlin there is no Long to pick. A number with a decimal part anywhere in the list becomes Double. Note that Swift's decoder is strict about numbers: decoding 3 into a Double property works, but decoding 3.5 into an Int fails.

Names are lowerCamelCase, so first_name becomes firstName. You then need a way to map the key. The synthesized default uses the property name, so either you add a CodingKeys enum with case firstName = "first_name", or you set decoder.keyDecodingStrategy = .convertFromSnakeCase. The strategy splits on underscores, lowercases the first word and capitalises the others (a key like user_ID becomes userId, not userID), and leaves leading and trailing underscores alone, so keys that are not plain snake_case still need a CodingKeys case.

Dates are the other decoder setting. JSON has no date type, so a Date property needs a dateDecodingStrategy: .iso8601 for strings like 2026-03-14T09:30:00Z, .secondsSince1970 or .millisecondsSince1970 for numbers, .formatted(DateFormatter) or .custom for anything else. This page types a key as Date only when every sample value is an ISO 8601 string.

first_name   -> firstName   (.convertFromSnakeCase, or case firstName = "first_name")
user_ID      -> userId      (strategy output; CodingKeys needed if you want userID)
_id          -> _id         (leading underscore kept)
key missing / null  ->  T?  ->  nil

Which JSONDecoder strategy decodes which JSON value?

Decoder settings that replace hand-written init(from:) code; each applies to the whole decoder
SettingValueReadsUse when
keyDecodingStrategy.useDefaultKeysKeys as writtenCodingKeys handle every rename (the default)
keyDecodingStrategy.convertFromSnakeCasefirst_name as firstNameThe whole API uses snake_case
dateDecodingStrategy.deferredToDateA number of seconds since 2001-01-01Rarely what a server sends (the default)
dateDecodingStrategy.iso8601"2026-03-14T09:30:00Z"The server sends ISO 8601 strings
dateDecodingStrategy.secondsSince19701773480600Unix timestamps in seconds
dateDecodingStrategy.millisecondsSince19701773480600000Unix timestamps in milliseconds (JavaScript style)
dateDecodingStrategy.formatted(formatter)Text in one DateFormatter formatA fixed non-ISO format
dateDecodingStrategy.custom { decoder in ... }Anything you parse yourselfMixed formats, fractional seconds

How to turn JSON into Swift Codable structs

  1. 1
    Paste the JSONUse a real response, with several array items if the API has optional keys. A syntax error is reported with its line and column.
  2. 2
    Choose how keys are matchedUse CodingKeys to keep each key exactly. Choose convertFromSnakeCase when the API is consistently snake_case and you want less code.
  3. 3
    Pick conformance and datesCodable if you also encode the models, Decodable if you only read them. Keep Date for ISO 8601 strings, or turn it off and keep Strings.
  4. 4
    Copy and decodePaste the structs into a .swift file and use the JSONDecoder lines at the end. Make sure the decoder settings match the output chosen here.

Frequently asked questions

Why does decoding fail with keyNotFound for a key I can see in the JSON?
The property name doesn't match the key. For first_name you need a CodingKeys case that maps to "first_name", or convertFromSnakeCase set on the decoder. Also check that the property isn't non-optional while the key is missing from one of the items; make it Optional.
Should I use CodingKeys or convertFromSnakeCase?
convertFromSnakeCase is less code when every key is snake_case, but it applies to the whole decoder and does odd things to acronyms: user_ID becomes userId. CodingKeys are explicit, work per struct, and are the only option when keys are mixed or contain dashes or spaces.
How do I decode a Date from JSON in Swift?
Set decoder.dateDecodingStrategy before decoding: .iso8601 for 2026-03-14T09:30:00Z, .secondsSince1970 or .millisecondsSince1970 for timestamps. With the default, .deferredToDate, a Date expects a number counted from 2001-01-01 and will fail on strings.
What should I do about a value that can be a string or a number?
Swift's Codable is typed, so one property can't take both. The usual answer is an enum with an init(from:) that tries each case, like the JSONValue enum this page adds for values it can't type. Fixing the API to be consistent is better.
Is the struct or the class better for decoded models?
Structs. Codable synthesis works for both, but structs are value types, copy safely across threads and Swift concurrency, and give you a memberwise initializer for tests. Use a class only when you need reference identity.
Why use Decodable instead of Codable?
Codable is just Decodable plus Encodable. If you only read an API response, Decodable says so and avoids requiring that every nested type can also be encoded, which matters for a type such as the JSONValue enum here.

Sources

Related tools

See all 135 free tools

Need a custom dev tool for your team?

We build internal tools, dashboards, APIs, and SaaS platforms. If you can describe it, we can ship it.

Built by CountryDevs · No signup · No ads · We count visits, never what you enter