JSON to Swift Converter
Convert JSON to Swift Online
Use our free json to swift converter to generate properly structured Swift Codable structs from any JSON data instantly. Whether you are building json to codable models for iOS applications, creating typed data structures for macOS development, or scaffolding API response types for SwiftUI projects, this tool produces clean, compilable Swift code from your JSON input.
What is JSON Format
JSON, short for JavaScript Object Notation, is a lightweight data interchange format that serves as the universal standard for web-based data communication. Its syntax of key-value pairs enclosed in curly braces and ordered arrays enclosed in square brackets makes it intuitive for both humans and machines. JSON supports strings, numbers, booleans, null, nested objects, and arrays as value types.
JSON has become the default format for REST API responses, NoSQL database storage, configuration files, and data exchange between services. Apple platforms provide native JSON support through the Foundation framework JSONDecoder and JSONEncoder classes, which handle serialization and deserialization between JSON data and Swift Codable types seamlessly. This tight integration makes JSON the primary data format for iOS, macOS, watchOS, and tvOS applications communicating with backend services.
What is Swift Codable Format
Swift Codable is a protocol composition of Encodable and Decodable that enables Swift types to be automatically serialized to and deserialized from external representations like JSON. Introduced in Swift 4, Codable leverages the Swift compiler to automatically synthesize the encoding and decoding logic for structs and classes whose properties all conform to Codable. This eliminates the manual parsing code that was previously required for JSON handling in Swift applications.
A Swift Codable struct declares its properties with type annotations, and the compiler generates the necessary CodingKeys enum and init(from:) and encode(to:) methods automatically. Swift supports primitive types including String, Int, Double, and Bool, as well as Optional for nullable values, Array for JSON arrays, and nested Codable types for JSON objects. Custom key mapping is achieved through a CodingKeys enum that maps between JSON key names and Swift property names. Codable has become the standard approach for JSON handling across all Apple platforms, used extensively in URLSession networking, SwiftUI data flow, and Core Data integration.
How the Conversion Works
Converting JSON to Swift Codable structs involves analyzing the structure and values of a JSON document to infer appropriate Swift types for each property. The converter parses the input JSON, examines each value to determine its Swift type, and generates struct definitions conforming to the Codable protocol. Strings become String, integers become Int, floating-point numbers become Double, booleans become Bool, null values become Optional types, arrays become Swift Array types, and nested objects become separate named Codable structs.
The conversion engine follows Swift naming conventions by converting JSON keys to camelCase property names and PascalCase struct names. When the original JSON key differs from the Swift property name, a CodingKeys enum is generated to handle the mapping. If your data originates in another format, you can first convert YAML to JSON before generating Swift structs. For working with your JSON data in other ways, try our JSON to TypeScript converter for web frontend types, or explore the JSON Schema generator for validating your API contracts. You can also convert JSON to XML for legacy system integration.
Syntax Comparison
The mapping between JSON data and Swift Codable structs is clean and intuitive. A JSON object like this:
// JSON
{
"user_name": "Alice",
"age": 30,
"active": true,
"score": 95.5
}
Generates the following Swift struct:
// Swift
struct Root: Codable {
let userName: String
let age: Int
let active: Bool
let score: Double
enum CodingKeys: String, CodingKey {
case userName = "user_name"
case age
case active
case score
}
}
JSON arrays are mapped to Swift Array types with appropriate element types. A JSON array of strings becomes [String], while an array of objects generates a separate Codable struct and uses an array of that struct type. Nested JSON objects produce additional named structs that conform to Codable. The CodingKeys enum is only generated when JSON key names differ from the Swift property names, keeping the output clean when no mapping is needed.
Common Use Cases
The most common use case for JSON to Swift conversion is creating model types for iOS and macOS applications that consume REST APIs. Swift developers using URLSession or Alamofire need Codable structs that match the JSON response structure for automatic decoding with JSONDecoder. Rather than manually writing these structs by inspecting API documentation, developers can paste a sample response and instantly generate the required type hierarchy.
Another frequent scenario involves SwiftUI application development, where JSON data from backend services needs to be decoded into observable model objects for display in views. Developers building widgets for iOS, watchOS complications, or App Clips also need lightweight Codable models for their data sources. Server-side Swift development with frameworks like Vapor uses the same Codable protocol for request and response handling, making this conversion equally valuable for backend Swift developers.
JSON to Swift Examples
The following examples demonstrate how various JSON structures are converted into Swift Codable struct definitions. These cover the most common patterns encountered when generating typed models from API responses and data sources.
A JSON object with nested structures generates multiple related Codable structs:
// JSON Input
{
"profile": {
"id": 42,
"displayName": "Alice Johnson",
"email": "alice@example.com",
"avatar": null,
"settings": {
"theme": "dark",
"notifications": true
},
"roles": ["admin", "editor"]
}
}
// Swift Output
struct Settings: Codable {
let theme: String
let notifications: Bool
}
struct Profile: Codable {
let id: Int
let displayName: String
let email: String
let avatar: String?
let settings: Settings
let roles: [String]
}
A JSON response with an array of objects and snake_case keys demonstrates CodingKeys usage:
// JSON Input
{
"search_results": [
{"item_id": 1, "item_name": "Widget", "unit_price": 9.99},
{"item_id": 2, "item_name": "Gadget", "unit_price": 24.99}
]
}
// Swift Output
struct SearchResult: Codable {
let itemId: Int
let itemName: String
let unitPrice: Double
enum CodingKeys: String, CodingKey {
case itemId = "item_id"
case itemName = "item_name"
case unitPrice = "unit_price"
}
}
struct Root: Codable {
let searchResults: [SearchResult]
enum CodingKeys: String, CodingKey {
case searchResults = "search_results"
}
}
Frequently Asked Questions
Does the converter generate structs or classes?
The converter generates Swift structs by default because structs are value types and the recommended choice for data models in Swift. Structs are copied on assignment, which provides thread safety and predictable behavior. If you need reference semantics for specific use cases like shared mutable state in SwiftUI with ObservableObject, you can change the struct keyword to class in the generated output and add the necessary protocol conformances.
How are JSON null values handled in Swift?
JSON null values are represented using Swift Optional types, denoted by the question mark syntax. A field that can be either a string or null becomes String? in the generated struct. When the JSON value is null, the Swift property will be nil after decoding. JSONDecoder handles Optional properties automatically, setting them to nil when the key is missing or the value is null in the JSON data.
When is a CodingKeys enum generated?
A CodingKeys enum is generated only when one or more JSON key names differ from the Swift property names. This typically happens when JSON uses snake_case naming like user_name while Swift convention uses camelCase like userName. If all JSON keys already match Swift naming conventions, the CodingKeys enum is omitted for cleaner output. You can also use JSONDecoder keyDecodingStrategy set to convertFromSnakeCase as an alternative to CodingKeys for snake_case JSON.
Can I use the generated structs with SwiftUI?
Yes, the generated Codable structs work seamlessly with SwiftUI applications. You can use them as the model type for State, Published, and ObservedObject properties. For SwiftUI lists and ForEach views, you may want to add Identifiable conformance by adding an id property or conforming to the protocol. The generated structs also work with SwiftUI environment objects and preference keys when wrapped in appropriate observable containers.
How are nested JSON objects handled?
Each nested JSON object generates a separate Swift struct conforming to Codable. The parent struct references the child struct as a property type, creating a clean type hierarchy. Struct names are derived from the JSON key names using PascalCase convention. This modular approach produces readable code that is easy to extend and test in your Swift projects.
Does the tool support let or var properties?
The converter generates properties using the let keyword by default, making the struct properties immutable after initialization. This follows Swift best practices of preferring immutability for data models. If you need mutable properties for two-way binding in SwiftUI or other mutation scenarios, you can change let to var in the generated output for the specific properties that need to be mutable.
Is the conversion performed securely?
Yes, the entire JSON to Swift conversion runs client-side in your browser. No data is transmitted to any external server, ensuring complete privacy and security. This makes the tool safe for converting JSON containing sensitive information such as API responses with user data or proprietary business logic. Your input never leaves your browser session and is never stored or logged.
How does this compare to generating Kotlin or TypeScript types?
Swift Codable structs are similar to Kotlin data classes in that both provide automatic method generation for data containers. TypeScript interfaces are compile-time only, while Swift structs exist at runtime with full type information. Swift CodingKeys provide more explicit control over JSON mapping than Kotlin serialization annotations. For web frontend needs, try our JSON to TypeScript converter instead.
FAQ
How does JSON to Swift Converter work?
Generate Swift Codable structs from JSON.