JSON to Swift
Generate Swift Codable types from a JSON sample. Properties are camelCased, and when any key differs from its property name a CodingKeys enum is emitted so JSONDecoder maps them correctly. Optional and nullable fields become Swift optionals.
How to generate Swift Codable structs from JSON
- Paste a JSON sample — ideally an array of several records, so optional fields are detected.
- Set the Root type name. Nested objects are named after the key that holds them, singularised for arrays.
- Keep struct unless you need reference semantics or inheritance.
- Tick public if the types live in a framework target that app code must import.
- Copy the code, or download it as a file.
Type mapping
- Integers →
Int; fractional →Double; booleans →Bool; strings →String. - Arrays →
[T]. - Objects → a nested Codable type.
- null / mixed →
AnyCodable, which is not in the standard library. Either add a package that provides it, or replace the field with a concrete type.
Dates and key strategies
Swift will not turn an ISO 8601 string into a Date unless you ask. Change the property type
to Date and set decoder.dateDecodingStrategy = .iso8601.
If every key in your API is snake_case, you can delete the generated
CodingKeys entirely and use
decoder.keyDecodingStrategy = .convertFromSnakeCase instead. Keep the explicit enum when the
naming is inconsistent — which, in real APIs, it usually is.
Getting good types out of a sample
Type inference from a sample is only as good as the sample. Three habits make the output far more useful:
- Paste an array, not one record. When you pass several records, a key missing from any of them is marked optional and a field that is sometimes a number and sometimes a float widens to a float. One record makes everything look required.
- Include the awkward cases. A record with a null, an empty array, and a missing optional key teaches the generator more than ten identical happy-path records.
- Check unions by hand. A field that holds different shapes in different records falls back to the language's "any" type. That is a signal your data has a variant the generator cannot express — model it explicitly.
Privacy
Nothing is uploaded. Inference and code generation run in this tab. No server sees the payload you paste — which matters, because real API responses tend to contain real user data.
FAQ
Why is CodingKeys missing on some types?
It is only emitted when at least one property name differs from its JSON key. When they all match, the synthesised conformance is correct and an explicit enum would be noise.
Should optional fields be Int? or use decodeIfPresent?
Declaring the property optional is enough — the synthesised initialiser calls decodeIfPresent for optionals automatically. You only write a custom init(from:) for defaults or transformations.
Can I get Objective-C compatible classes?
Not directly. Switch to class, then add @objc and inherit from NSObject by hand — Codable and Objective-C bridging do not overlap cleanly.