JSON to Swift
Convert any JSON object or array into clean Swift structs conforming to Codable instantly. Generates correct Swift type mappings, Optional properties for nullable fields, nested struct decomposition, CodingKeys enums for camelCase JSON keys, and array type annotations. Runs entirely in your browser — no data transmitted, no Xcode required.
Convert any JSON object or array into clean Swift structs conforming to Codable instantly. Generates correct Swift type mappings, Optional properties for nullable fields, nested struct decomposition, CodingKeys enums for camelCase JSON keys, and array type annotations. Runs entirely in your browser — no data transmitted, no Xcode required.
This tool is designed to provide a seamless experience for developers by handling complex operations directly in your browser with maximum speed and security.
A JSON to Swift converter reads a JSON object or array and generates Swift struct definitions that conform to the Codable protocol, ready to use with JSONDecoder to parse API responses and JSONEncoder to serialise data back to JSON in your iOS, macOS, watchOS, or tvOS application.
Codable is a Swift type alias for the combination of Decodable and Encodable protocols, introduced in Swift 4. It is the standard approach to JSON handling in Swift and the one Apple recommends for all new projects. Understanding what Codable actually does under the hood helps explain why generated structs need to be structured in a specific way to work correctly.
When you call JSONDecoder().decode(MyType.self, from: data), the Swift compiler synthesises a CodingKeys enum and an init(from:) initialiser for your struct automatically — but only if every property name in your struct exactly matches the corresponding key in the JSON. This is the core constraint. REST APIs almost universally use camelCase JSON keys (firstName, isActive, joinedAt). Swift naming conventions follow camelCase too, which means property names usually match — but when they do not, or when the JSON key contains characters not valid in Swift identifiers, you need an explicit CodingKeys enum that maps each Swift property name to the corresponding JSON key string. This tool generates that enum automatically whenever the mapping is non-trivial.
Swift's type system is strict in ways that matter for JSON parsing. A property declared as String cannot hold nil — if the JSON contains null for that key, or omits the key entirely, JSONDecoder throws a keyNotFound or valueNotFound DecodingError and your entire decode call fails. Nullable and optional JSON fields must be declared as Optional in your Swift struct: var email: String? rather than var email: String. The question mark is not optional (pun intended) — it is required for correctness. This tool infers which fields should be Optional by inspecting your sample JSON for null values and, when you provide an array, by detecting fields that are absent from some records.
Nested JSON objects become nested Swift structs. Each level of nesting generates its own struct definition with its own Codable conformance. Swift's synthesised Codable implementation handles the nesting automatically — you just need the struct hierarchy to mirror the JSON hierarchy, which is exactly what this tool produces.
Read the Full GuideThis tool takes a JSON object or array and generates Swift struct definitions conforming to Codable that you can drop directly into an Xcode project and use with JSONDecoder to parse API responses. The type mapping covers all JSON primitive types with the correct Swift equivalents. JSON strings become String. JSON integers become Int. JSON floating-point numbers become Double. JSON booleans become Bool. JSON null values and fields that are absent from some records in an array input become Optional properties — String?, Int?, Bool?, and so on — with correct handling in the generated struct so that JSONDecoder does not throw when the value is absent or null. Arrays of primitives generate typed Swift array properties: [String] for string arrays, [Int] for integer arrays, [Double] for number arrays. Arrays of objects generate a [NestedType] property where NestedType is a separately defined Codable struct generated from the shape of the array elements. Nested JSON objects generate separate named Swift struct definitions. Each nested struct gets its own Codable conformance and is referenced by name in the parent struct. This mirrors Swift's idiomatic approach to nested data — not a dictionary of type [String: Any], which loses all type safety and requires manual casting at every access, but a proper typed struct that your editor can autocomplete and your compiler can validate. When your JSON keys use camelCase and your Swift property names match exactly, no CodingKeys enum is needed and the compiler synthesises everything. When there is a mismatch — JSON key uses snake_case, or contains a hyphen, or conflicts with a Swift keyword — the tool generates an explicit CodingKeys enum with the correct rawValue string for each case. The generated CodingKeys enum follows Swift convention: each case is the Swift property name with a string rawValue of the original JSON key. The output also includes a practical JSONDecoder configuration hint. JSONDecoder has a keyDecodingStrategy property — setting it to .convertFromSnakeCase tells the decoder to automatically convert snake_case JSON keys to camelCase Swift property names without needing an explicit CodingKeys enum. For APIs that follow strict snake_case naming, this is cleaner than generating CodingKeys for every property. The tool notes when this strategy would apply to your JSON.
Paste your JSON into the input editor. Use a real API response sample if you have one — the more representative your input, the more accurate the generated struct types will be. If you have access to multiple response samples, paste an array of objects so the tool can detect fields that are absent from some records and mark them as Optional correctly.
Click Generate Swift Struct. The output panel shows the complete Swift struct hierarchy, including all nested struct definitions and any required CodingKeys enums, with Codable conformance on each struct.
Review the generated Optional annotations carefully. A field typed as String? means the JSON key can be absent or null. If you know from your API documentation that a field is always present, you can change String? to String — but only if you are certain, because a wrong non-optional annotation will throw a DecodingError when a null or missing value arrives. When in doubt, keep Optional.
Check the type annotations for numeric fields. The generator uses Int for integer JSON values and Double for decimal values. If a field represents a monetary amount or measurement where precision matters, confirm that Double is appropriate or consider using Decimal for cases where floating-point precision errors are unacceptable.
Review any generated CodingKeys enums. These appear when a JSON key does not match a valid Swift identifier or when the naming convention conversion requires explicit mapping. Confirm that each rawValue string exactly matches the corresponding JSON key — a single character mismatch will cause JSONDecoder to silently skip that field and use the default value (nil for optionals, which means missing data without an error).
Copy the output and paste it into your Xcode project. Place nested struct definitions in the same file as the parent struct or extract them into their own files — both approaches work. Add import Foundation at the top of the file if it is not already imported, since JSONDecoder and JSONEncoder are Foundation types.
Use JSONDecoder().decode(YourRootStruct.self, from: jsonData) to parse your API response. Wrap the call in a do-catch block to handle DecodingError explicitly — catching the error lets you log the specific field and key path that failed, which is essential for debugging when an API changes its response shape.
Swift is a strongly typed language, and that type system is one of its biggest strengths for building reliable iOS and macOS applications. JSON, by contrast, is completely untyped — any key can hold any value, any key can be absent, and the structure can vary between responses. Bridging these two worlds correctly and idiomatically is something every Swift developer has to do repeatedly, and it involves enough edge cases that doing it by hand is error-prone even for experienced engineers. The most common mistake I see in Swift codebases that predate a developer's understanding of Codable is the JSONSerialization approach — parsing JSON into [String: Any] and then force-casting values: let name = data["name"] as! String. This works until the API returns null for name, or omits the key, or returns an integer instead of a string, at which point the force cast throws an uncaught exception and your application crashes. The crash is not always immediate — it might only happen on a specific user's data, in a specific app state, in a specific response from the API. These are the crashes that take the longest to debug because they are not reproducible in development. Codable with properly typed structs converts that class of crash into a compile-time or decode-time error. If the API returns null for a field declared as String (non-optional), JSONDecoder throws a DecodingError — a structured, catchable error that you handle explicitly. If the API omits a key, same thing. Your application does not crash silently; it fails loudly at the boundary where external data enters your system, which is exactly where you want failures to be visible. The nested struct pattern matters for maintainability. When you represent a deeply nested API response as a hierarchy of typed structs rather than a chained dictionary of [String: Any], every level of the hierarchy is visible in your source code, autocompletable in Xcode, searchable with Find in Project, and refactorable with Xcode's rename tool. Accessing response.user.profile.timezone is type-safe and editor-assisted. Accessing data["user"]?["profile"]?["timezone"] as? String is none of those things. Writing Codable structs from a JSON payload by hand is one of the most mechanical tasks in iOS development. You look at each key, decide on a Swift type, decide whether it is optional, write the property, handle CodingKeys if the names do not match, write the nested structs, check that every level conforms to Codable. For a ten-field response with two levels of nesting, this takes five to ten minutes with no interesting engineering decisions involved. This tool does it in five seconds. You still need to review and potentially adjust the output — the tool cannot know whether a field that looks like an integer in your sample might be a Double in production, or whether a non-null field in your sample might be null in edge cases — but it eliminates the mechanical scaffolding entirely.
Full Codable conformance generated automatically — works directly with JSONDecoder and JSONEncoder
Correct Swift type mapping — String & Int & Double & Bool & Optional and typed arrays inferred from JSON values
Optional properties generated for null JSON fields — prevents DecodingError crashes on missing or null values
Nested JSON objects generate separate named Codable structs mirroring the JSON hierarchy
CodingKeys enum generated automatically when JSON key names require explicit mapping
Handles arrays of primitives as [String] & [Int] & [Double] and arrays of objects as [NestedStruct] & import Foundation included automatically — no additional setup required in Xcode
Runs entirely in your browser — zero data transmitted & no Xcode or Swift toolchain required
Generating Codable Swift structs for parsing REST API responses in an iOS or macOS application
Scaffolding Swift model types when integrating a new third-party API or SDK into an Xcode project
Creating typed Swift data models for a SwiftUI application that displays data from a JSON API
Generating Swift structs for decoding webhook payloads received in a server-side Swift service using Vapor or Hummingbird
Building typed response models for URLSession dataTask or async/await network calls
Creating Swift Codable models for local JSON configuration files bundled in an iOS app
Prototyping a data model from an API response before writing full network layer code
Generating Swift structs for parsing JSON responses in a WatchOS or tvOS companion application
Example Input
{
"id": 1,
"name": "Priya Singh",
"email": "priya@techcorp.io",
"role": "Principal Engineer",
"yearsExperience": 15,
"isActive": true,
"joinedAt": "2019-03-12",
"salary": 185000.00,
"reportsTo": null,
"skills": ["Swift", "Go", "PostgreSQL", "System Design"],
"profile": {
"bio": "15 years in distributed systems and data infrastructure.",
"timezone": "Asia/Kolkata",
"githubHandle": "priyasingh-eng",
"avatarUrl": "https://techcorp.io/avatars/priya.jpg"
}
}Example Output
import Foundation
struct Profile: Codable {
let bio: String
let timezone: String
let githubHandle: String
let avatarUrl: String
enum CodingKeys: String, CodingKey {
case bio
case timezone
case githubHandle
case avatarUrl
}
}
struct User: Codable {
let id: Int
let name: String
let email: String
let role: String
let yearsExperience: Int
let isActive: Bool
let joinedAt: String
let salary: Double
let reportsTo: String?
let skills: [String]
let profile: Profile
enum CodingKeys: String, CodingKey {
case id
case name
case email
case role
case yearsExperience
case isActive
case joinedAt
case salary
case reportsTo
case skills
case profile
}
}DecodingError.keyNotFound — key not found for a field that exists in the JSON
Fix: The CodingKeys rawValue for this property does not exactly match the JSON key. Check for capitalisation differences, underscores, or Unicode differences. If the JSON key is 'firstName' and your CodingKeys case has rawValue 'first_name', it will not match. Fix the rawValue to match the JSON key exactly. If you do not have a CodingKeys enum and are relying on compiler synthesis, ensure the Swift property name matches the JSON key exactly including case.
DecodingError.typeMismatch — expected String but found Int (or similar type mismatch)
Fix: The Swift property type does not match the JSON value type for this field. The most common case is a JSON number being decoded into a String property, or a JSON string being decoded into an Int property. Change the property type to match the actual JSON value type. If the field can legitimately hold multiple types (rare but possible with poorly designed APIs), use AnyCodable from the AnyCodable package, or write a custom init(from:) decoder for that property.
DecodingError.valueNotFound — value not found for a non-optional property
Fix: The JSON contains null for this key, or the key is absent entirely, but the Swift property is declared as a non-optional type (String instead of String?). Change the property declaration from String to String? to allow nil values. If you are certain the API should never return null for this field, the error indicates an API contract violation — log it and investigate the API response rather than silently ignoring it.
Fatal error: Unexpectedly found nil while unwrapping an Optional value — runtime crash on Optional property access
Fix: A property declared as Optional (String?) is nil at the point where you are force-unwrapping it with ! or accessing it without a nil check. Use optional binding instead: if let value = myStruct.optionalField { ... } or use the nil-coalescing operator for a default: myStruct.optionalField ?? 'default'. Never force-unwrap Codable Optional properties unless you have already confirmed they are non-nil through an explicit check.
Compile error: Type 'MyStruct' does not conform to protocol 'Decodable'
Fix: One of the properties in your struct has a type that does not itself conform to Codable. This usually means a nested struct is missing its Codable conformance declaration, or you have used a type like UUID, URL, Date, or a custom type without verifying it conforms to Codable. UUID, URL, and Date all conform to Codable in Foundation. Custom types need explicit Codable conformance. Check every property type in the error's struct and trace which one is missing Codable.
Removing Optional annotations from fields that look non-null in your sample — the tool marks a field as Optional (String?) when it is null in your JSON or absent from some records in an array. If you change it to a non-optional String because your sample happens to always have a value, your app will crash with a DecodingError the first time the API returns null or omits that field for a real user. Trust the Optional annotations and only remove them when your API documentation explicitly guarantees the field will always be present and non-null.
Mismatching a CodingKeys rawValue with the actual JSON key — CodingKeys maps a Swift property name to a JSON key string via a rawValue. If the rawValue does not exactly match the JSON key — different capitalisation, an extra underscore, a typo — JSONDecoder silently skips that field. Non-optional fields that are skipped throw a keyNotFound DecodingError. Optional fields that are skipped silently become nil. Both outcomes are wrong. Always verify every CodingKeys rawValue against the actual JSON key character by character.
Using Int where the API can return Double — an API field that returns 15 in your test data will be typed as Int. If the same field returns 15.5 for some users (fractional years, percentage values, measurements), JSONDecoder will throw a typeMismatch DecodingError because it cannot decode a JSON number with a decimal point into a Swift Int. Review every numeric field against your API documentation and use Double for any field that could be non-integer.
Using let for properties that you later need to mutate — generated structs use let for all properties by default, which makes them immutable value types. If you need to update a property after decoding — setting a computed display value, populating a field after a secondary API call, or using the struct as a form backing model — you need var. Change let to var for those specific properties. Immutable by default is the correct Swift idiom; var should be a deliberate choice, not the default.
Forgetting to add the struct file to the correct target in Xcode — new Swift files added to an Xcode project are sometimes added only to the main app target and not to test targets or framework targets. If your generated struct is not in scope when running unit tests, you will get a 'use of undeclared type' compile error in test files even though the struct compiles fine in the app. When adding the generated file, check the Target Membership checkboxes in the File Inspector.
JSON Cheatsheet
Interactive reference guide for valid JSON syntax, data types, parsing/stringifying methods, schema validation rules, and language integrations.
Regex Cheatsheet
Interactive guide to Regex anchors, character classes, quantifiers, lookarounds, capturing groups, and search flags.
HTTP Headers Cheatsheet
Complete guide to standard and security HTTP headers including Authorization, CORS control, caching policies, and CSP directives.
SQL Cheatsheet
Complete guide to SQL statements including SELECT queries, WHERE filters, aggregate functions, JOIN types, and DDL commands.
Does it support Optional types for null JSON fields?
Yes. Fields that are null in your JSON sample are generated as Optional properties — String?, Int?, Bool?, and so on. When you provide a JSON array as input, fields that are absent from some objects in the array are also typed as Optional, because JSONDecoder will encounter records where the key does not exist and must not throw. Optional properties in a Codable struct are decoded as nil when the key is absent or the value is null, without throwing a DecodingError. Non-optional properties throw DecodingError.valueNotFound or DecodingError.keyNotFound in those cases.
What is Codable and why does every generated struct use it?
Codable is a Swift type alias for Decodable & Encodable — a single protocol that lets a type be both decoded from JSON (or other formats) and encoded back to JSON. Adding Codable conformance to a struct and conforming to it correctly (either through compiler synthesis or manual implementation) is the standard, Apple-recommended approach to JSON handling in all Swift versions from Swift 4 onward. JSONDecoder and JSONEncoder — Foundation types available on all Apple platforms and in server-side Swift — both require their input and output types to conform to Codable. Every generated struct includes this conformance so it works with these APIs immediately.
When does the generator produce a CodingKeys enum?
Swift's compiler synthesises CodingKeys automatically only when every Swift property name exactly matches the corresponding JSON key. When there is a mismatch — a JSON key uses snake_case while the Swift property uses camelCase, or a JSON key contains a hyphen or other character not valid in a Swift identifier, or a JSON key conflicts with a Swift keyword — you need an explicit CodingKeys enum. The generator produces one whenever a mapping is non-trivial. You can also avoid CodingKeys entirely for snake_case APIs by setting JSONDecoder's keyDecodingStrategy to .convertFromSnakeCase, which performs the conversion automatically.
Should I use struct or class for the generated types?
The generator produces struct definitions, which is the correct Swift idiom for data model types. Swift structs are value types — they are copied on assignment, which eliminates a whole class of shared-mutable-state bugs that are common with class-based models. Codable works identically with both structs and classes. The only reason to use class for a Codable model type is if you need reference semantics — for example, if multiple parts of your application need to observe and react to changes in the same model instance. For pure data models representing API responses, struct is always the right choice.
How do I handle a JSON date string as a Swift Date type?
The generator types date string fields as String because it cannot determine from the JSON value alone whether a string like '2019-03-12' should be a Swift Date or just a String in your model. To decode it as a proper Date, change the property type from String to Date in the generated struct, then configure your JSONDecoder with the appropriate date decoding strategy before calling decode(): decoder.dateDecodingStrategy = .iso8601 for ISO 8601 strings, or .formatted(DateFormatter) for custom date formats. Using Date instead of String gives you full Date arithmetic, comparison, and formatting capabilities in your application code.
Can I use the generated struct with SwiftUI?
Yes, directly. SwiftUI views can display properties from a Codable struct with no additional configuration. For reactive UI updates when the model changes, wrap the struct in a class that conforms to ObservableObject and publish the struct as a @Published property, or in Swift 5.9+ use @Observable from the Observation framework. The generated Codable struct itself is the data layer — the reactive layer on top is a separate concern and is independent of how the struct was generated.
Is the generated code compatible with older iOS versions?
Codable was introduced in Swift 4 alongside iOS 11 (2017). The generated structs use no APIs introduced after that baseline, so they are compatible with any iOS deployment target from iOS 11 onward. The typing syntax (Optional, typed arrays) is standard Swift and compatible from Swift 4.0 through the current version. If you are maintaining a project with an iOS 10 or earlier deployment target — which is increasingly rare — you would need to use JSONSerialization with manual type casting instead of Codable, and the generated struct would not apply.
Is my JSON data sent to any server?
No. The entire conversion runs in JavaScript in your browser. Your JSON is never transmitted to any external server, never logged, and never stored anywhere.
Beyond Codable: Modern Strategies for Mapping JSON to Swift Models in 2026
Beyond Codable: Modern Strategies for Mapping JSON to Swift Models in 2026. In-depth guide covering manual Codable limitations, Swift Macros, code generation, property wrappers, polymorphic responses, performance, and real-world architecture from a Principal Software Engineer with 15+ years experience.
How to Convert JSON to Dart Classes for Flutter – Complete In-Depth Guide (2026)
How to convert JSON to Dart classes for Flutter in 2026. In-depth guide covering Dart model best practices, null safety, immutable classes, code generation with json_serializable & freezed, Flutter integration with Riverpod, and real-world architecture tips from a Principal Software Engineer with 15+ years experience.
What is JSON? How to Format, Validate & Use It (Complete Guide 2026)
What is JSON? How to Format, Validate & Use It (Complete Guide 2026). In-depth explanation of JSON syntax, real-world use cases, formatting best practices, common mistakes, advantages, disadvantages, and expert tips from a Principal Software Engineer with 15+ years experience.
Recent Activity
No recent activity