Youtilities

Popular

All tools

JSON to Swift Codable

Generate Swift Codable structs with CodingKeys from any JSON.

Runs in your browser. Nothing is uploaded.

Input

Waiting for JSON

Swift
Swift types appear here.

What this does

Paste JSON and get Swift structs that conform to Codable, ready for JSONDecoder. Nested objects become their own structs; arrays of objects are merged into one struct.

Optionals

A key that is missing from some items, or sometimes null, becomes an optional such as String?. Whole numbers are Int, decimals Double. Values with no clear type use AnyCodable, a small community package, since Codable has no Any.

Names

Properties are camelCase. When that differs from the JSON key (first-name → firstName) a CodingKeys enum maps it back. Two objects with the same shape share one struct.

Decoding with JSONDecoder

Read data with let root = try JSONDecoder().decode(Root.self, from: data). When any property name differs from its key, the struct gets a CodingKeys enum that lists every property, as Swift requires. Do not also set keyDecodingStrategy to convertFromSnakeCase: that converts the keys before they are matched against CodingKeys, and the renamed properties stop matching. Swift keywords used as keys, such as default or class, are kept with backticks.

Common decoding errors

keyNotFound means the real data is missing a key that was present in your sample; make that property optional or turn on All optional. A decimal such as 1.5 cannot be decoded into an Int, so include decimals in the sample if a field can have them. Dates arrive as String; change the type to Date and set decoder.dateDecodingStrategy = .iso8601 for ISO timestamps. Properties are declared with let; change them to var if you need to modify values after decoding.

All json tools