How it works
Paste a JSON sample and get Swift structs for JSONDecoder and JSONEncoder:
- Every object becomes a
structconforming toCodable(orDecodable), named after its property (customer→Customer,items→Item). The root isRootunless you rename it. - Properties are lowerCamelCase. A
CodingKeysenum is added only when some name differs from its key. - Arrays of objects are merged: keys that only some items have become optionals, and synthesized
DecodableusesdecodeIfPresentfor them. - Types are
String,Int,Double,Bool,[T]for arrays andT?for nullable or optional values. - A root array or primitive becomes a
typealias, for exampletypealias 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:
letfor immutable models, orvarif you edit them after decoding. - Conform to:
Codable, orDecodablewhen you only read JSON. TheJSONValuehelper then has noencode(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 toDateand setdecoder.dateDecodingStrategy = .iso8601. - Whole-number prices.
25becomesInt, and a later25.5fails withtypeMismatch. UseDoubleorDecimal.
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