JSON to Swift

Generate Swift Codable structs with CodingKeys from JSON.

Runs in your browser Instant No sign-up
Properties
Conform to
JSON input
Swift

Paste, type or drop a file — output appears as you type.

Waiting for input
Processed locally · nothing is uploadedProcessed locally

How it works

Paste a JSON sample and get Swift structs for JSONDecoder and JSONEncoder:

  1. Every object becomes a struct conforming to Codable (or Decodable), named after its property (customer → Customer, items → Item). The root is Root unless you rename it.
  2. Properties are lowerCamelCase. A CodingKeys enum is added only when some name differs from its key.
  3. Arrays of objects are merged: keys that only some items have become optionals, and synthesized Decodable uses decodeIfPresent for them.
  4. Types are String, Int, Double, Bool, [T] for arrays and T? for nullable or optional values.
  5. A root array or primitive becomes a typealias, for example typealias Root = [RootItem].

Example

{
  "user_id": 42,
  "name": "Linh",
  "tags": ["admin"],
  "addresses": [
    { "city": "Hanoi", "zip": "100000", "note": null },
    { "city": "HCMC", "zip": "700000", "primary": true, "note": "Gate 2" }
  ]
}

becomes

import Foundation

struct Root: Codable {
    let userId: Int
    let name: String
    let tags: [String]
    let addresses: [Address]

    enum CodingKeys: String, CodingKey {
        case userId = "user_id"
        case name
        case tags
        case addresses
    }
}

struct Address: Codable {
    let city: String
    let zip: String
    let note: String?
    let primary: Bool?
}

Options

  • Root name: name of the top-level struct.
  • Properties: let for immutable models, or var if you edit them after decoding.
  • Conform to: Codable, or Decodable when you only read JSON. The JSONValue helper then has no encode(to:).

Reserved words and odd keys

Swift keywords are escaped with backticks, so class, default and even self work as property names, and the CodingKeys case keeps the key without a raw value (case `class`). Other keys get a raw value. For {"class": "vip", "first name": "Linh", "2fa": true}:

struct Root: Codable {
    let `class`: String
    let firstName: String
    let field2fa: Bool

    enum CodingKeys: String, CodingKey {
        case `class`
        case firstName = "first name"
        case field2fa = "2fa"
    }
}

Structs that would shadow types the code or Foundation uses (String, Data, Date, URL, Type and so on) get a Type suffix, so a "data": {…} key gives DataType.

Decoding

let root = try JSONDecoder().decode(Root.self, from: data)

let or var?

let properties make each decoded value immutable, which suits API responses that you only read. Choose var when the app edits a model and encodes it back, for example a settings screen. Structs are value types either way, so a copy never changes the original.

Common mistakes

  • Generating from a single object. Nothing is optional, and a later response without a key fails with keyNotFound. Paste several real responses.
  • Dates as strings. Timestamps come out as String. Change them to Date and set decoder.dateDecodingStrategy = .iso8601.
  • Whole-number prices. 25 becomes Int, and a later 25.5 fails with typeMismatch. Use Double or Decimal.

Building the Android or backend side too? See JSON to Kotlin, JSON to Rust and JSON to TypeScript.

Frequently asked questions

When is a CodingKeys enum generated?

When at least one property name differs from its JSON key: snake_case keys (`user_id` → `userId`), keys with spaces or dashes, keys starting with a digit, or keys in a different case such as `ID`. Swift then needs every property listed, so all cases appear, with a raw value only where the key differs.

Why not use keyDecodingStrategy = .convertFromSnakeCase?

You can: it works for plain snake_case APIs. Explicit CodingKeys also handle keys the strategy cannot convert (spaces, leading digits, mixed conventions) and keep encoding and decoding symmetric without configuring the encoder and decoder.

What is the JSONValue enum at the end?

Swift has no Codable `Any`. When the sample has no single type for a value (all null, an empty array or mixed types), the property uses a small `JSONValue` enum that decodes any JSON. It is only emitted when needed; replace it with a real type once you know it.

How are numbers typed?

`Int` for whole numbers (64-bit on all current Apple platforms) and `Double` when any value has a fraction. Integers beyond 64 bits become `Decimal` with a warning, because JSONDecoder may round very long numbers.

Is my JSON uploaded?

No. The structs are generated entirely in your browser; nothing is sent to a server.

Last updated