About Convert JSON to Swift
Paste a JSON object and get Swift struct definitions with Codable conformance. Handles nested objects (each generates its own struct), arrays (typed as [T]), strings, integers, doubles, booleans, and null (typed as optional). Generated code is compatible with Swift 4.1+ and works with JSONDecoder out of the box.
Frequently Asked Questions
What is JSON to Swift struct generation?
JSON to Swift struct generation analyses a JSON sample and produces Swift struct definitions conforming to Codable. Each key becomes a property, and CodingKeys are generated when the JSON key name differs from Swift naming convention, making the struct ready for JSONDecoder.
How do I decode JSON with missing or optional fields using Codable?
Mark fields that may be absent as Optional (String?, Int?, etc.) and provide a default value of nil. If the key is missing from the JSON, JSONDecoder silently sets the property to nil instead of throwing. Use decodeIfPresent(_:forKey:) in a custom init(from:) when you need different behaviour for missing vs null values.
How do I map snake_case JSON keys to camelCase Swift properties?
Set decoder.keyDecodingStrategy = .convertFromSnakeCase before decoding. This automatically converts first_name to firstName for all properties without needing CodingKeys. For non-standard mappings, implement CodingKeys manually. The generator outputs camelCase properties following Swift naming conventions.
Should I generate a Swift struct or a class for JSON models?
Prefer struct for JSON models — structs are value types, thread-safe by default, and more idiomatic in Swift. Use class when you need reference semantics, inheritance, or need to conform to ObservableObject for SwiftUI. Both work identically with Codable for JSON decoding.
How do I use the generated Codable struct with URLSession?
let task = URLSession.shared.dataTask(with: url) { data, _, _ in guard let data = data else { return }; let obj = try? JSONDecoder().decode(RootStruct.self, from: data) }; task.resume(). For async/await: let (data, _) = try await URLSession.shared.data(from: url); let obj = try JSONDecoder().decode(RootStruct.self, from: data).
Advertisement300 × 250
Advertisement300 × 250