JSON1 / JSON to Swift
JSON to Swift
Generate Swift structs conforming to Codable from a JSON sample. CodingKeys are emitted only when a key differs from its property name, so simple models stay readable.
Processed locally·Your data never leaves your device
InputJSON
ReadyOutputSwift
Converted output appears here as you type.
Good to know
- Every record in an array is inspected, not just the first, so a field that appears in only some of them is typed as optional rather than required.
- Identical nested shapes are emitted once and reused, and reserved words are renamed to something legal in this language.
About this tool
Conforming a struct to Codable is all Swift needs to decode JSON, provided the property names line up with the keys. This generates the structs, and the CodingKeys for the cases where they do not.
Keys become camelCase properties and nested objects are hoisted into their own structs, so the decoded value is fully typed.
- Why do only some structs have a CodingKeys enum?
- It is emitted only when at least one key differs from its property name. Where the names already match, Codable handles the mapping on its own and the enum would be dead weight.
- Why a struct rather than a class?
- A decoded API response is a value: two responses with the same fields are the same response, and nothing should be mutating one from a second reference. Structs give you that plus a free memberwise initialiser. Use a class only if you actually need identity or inheritance.
- How are optional fields decided?
- Every record in an array is inspected, not just the first. A field that appears in some records and not others is typed as optional, and a value that is sometimes null widens accordingly. Generators that read only the first element get this wrong on exactly the payloads where it matters.
- What happens to a key that is a reserved word?
- It is renamed to something legal in the target language, and where the language supports it, an annotation records the original JSON key so serialisation still round-trips.