About the JSON to Swift
Generate Swift Codable models from JSON. Properties use camelCase, CodingKeys map them back to the original JSON keys, and optional or nullable values become Swift optionals.
Key features
- Swift structs or final classes conforming to Codable
- CodingKeys generated only when names differ from keys
- camelCase properties; Swift keywords escaped with backticks
- Optionals for nullable and missing values
- let or var properties
- A small JSONValue enum for values of unknown type
Swift Codable models from JSON
iOS, macOS and server-side Swift apps decode JSON with Codable. Paste a sample response and get Codable structs with the right property types, optionals and CodingKeys.
Example
[
{ "user_id": 7, "name": "Ada", "nickname": "ada", "score": 4.5 },
{ "user_id": 8, "name": "Alan", "nickname": null, "score": 3 }
]
struct User: Codable {
let userId: Int
let name: String
let nickname: String?
let score: Double
enum CodingKeys: String, CodingKey {
case userId = "user_id"
case name
case nickname
case score
}
}
typealias UserList = [User]
let users = try JSONDecoder().decode([User].self, from: data)
Notice that score became Double because one item had 4.5, and nickname became optional because one item had null.
Type mapping
| JSON | Swift |
|---|---|
"text" | String |
42 | Int |
3.14 | Double |
true | Bool |
[...] | [T] |
{...} | struct |
| null or missing | T? |
| unknown | JSONValue? |
Tips
- Dates: change
StringtoDateand setdecoder.dateDecodingStrategy = .iso8601. - SwiftUI: add
Identifiable(andHashable) conformance to use models directly inListandForEach. - Errors: decoding errors name the exact key path. Print
errorin acatchto see it.
Related tools
Building the Android app as well? Use JSON to Kotlin. For Flutter, see JSON to Dart.
How to use the JSON to Swift
- Paste your data into the input box, upload a file, or click Sample to try it out.
- Adjust the options above the editor if you need to (indentation, delimiter, and so on).
- The Swift appears instantly in the output panel. Any errors are shown with their line and column.
- Click Copy to copy the result, or Download to save it as a file.