About the JSON to Swift Codable Generator
With Codable, decoding JSON in Swift is one line once the structs exist. This generator writes them: a struct per object shape, each with let properties typed String, Int, Double, Bool or an array of the nested type, and conforming to Codable so both decoding and encoding work.
Types are read from the sample, which is the whole method and also its limit. A number with no fractional part is typed Int while one with a decimal point becomes Double, so a price that reads 20 in your sample and 19.99 in production throws a decoding error at runtime rather than rounding, because JSONDecoder refuses to lose precision. Widen money and measurement fields to Double before shipping.
Property names are converted to camelCase. If your JSON uses snake_case keys, set decoder.keyDecodingStrategy = .convertFromSnakeCase rather than writing CodingKeys by hand. Null values become optional Strings as a placeholder; change them to the real type once known.
Optional fields are not inferred from a single sample. Every property is emitted non-optional, and decoding throws keyNotFound the first time a real response leaves one out, so add ? to any property the API documents as optional. Modelling a REST response for a new screen is the typical use, and the same JSON produces data classes in JSON to Kotlin and interfaces in JSON to TypeScript when more than one client consumes the endpoint.
How to use
- Paste a JSON sample on the left and set the root struct name.
- Copy the structs into a Swift file.
- Decode with
try JSONDecoder().decode(Root.self, from: data).
Common questions
- Do I need CodingKeys?
- Only if a key cannot be handled by a keyDecodingStrategy, for example a key with a dash. The generator keeps the output short by not emitting them.
- Why let instead of var?
- Decoded models are usually immutable. Change to var where you need to edit fields.
- Are classes supported?
- Structs are emitted because they are the recommended choice for value data. Replace the keyword if you need reference semantics.