JSON to Swift Codable
Paste JSON and get Swift structs that conform to Codable, with CodingKeys where JSON keys differ from Swift names. Free, no signup, and generated in your browser so nothing is uploaded.
16 lines · processed in your browser, nothing is uploaded
Swift output · Root.swift
Generated code appears here.Example: JSON to Swift
This JSON sample, with the root type named User, produces the Swift below using the default options.
{
"id": 1024,
"name": "Ada Lovelace",
"email": "ada@example.com",
"active": true,
"score": 98.5,
"tags": [
"admin",
"beta"
],
"address": {
"city": "London",
"postcode": "NW1 6XE"
}
}// This file was generated from JSON Schema using quicktype, do not modify it directly.
// To parse the JSON, add this file to your project and do:
//
// let user = try? JSONDecoder().decode(User.self, from: jsonData)
import Foundation
// MARK: - User
struct User: Codable {
let id: Int
let name: String
let email: String
let active: Bool
let score: Double
let tags: [String]
let address: Address
enum CodingKeys: String, CodingKey {
case id = "id"
case name = "name"
case email = "email"
case active = "active"
case score = "score"
case tags = "tags"
case address = "address"
}
}
// MARK: - Address
struct Address: Codable {
let city: String
let postcode: String
enum CodingKeys: String, CodingKey {
case city = "city"
case postcode = "postcode"
}
}
How to convert JSON to Swift
- 1Paste a JSON object or array into the input.
- 2Select Swift as the output language.
- 3Name the root struct, for example Album.
- 4Adjust options such as struct or class output if available.
- 5Copy the code into a .swift file and decode with JSONDecoder.
Codable and CodingKeys
Codable is a type alias for Encodable & Decodable. When every property name matches a JSON key, the compiler synthesizes the coding logic for you.
When names differ, add a nested enum CodingKeys: String, CodingKey with one case per property, such as case userID = "user_id". Every stored property must be listed, or it needs a default value.
Decoding in practice
Decode with try JSONDecoder().decode(Album.self, from: data). For snake_case APIs you can set decoder.keyDecodingStrategy = .convertFromSnakeCase instead of writing CodingKeys by hand.
Dates need a strategy too: set dateDecodingStrategy to .iso8601 or a custom formatter, or keep the field as String.
Optionals
Declare a property as an optional (String?) when the key may be missing or null; synthesized decoding then uses decodeIfPresent. A non-optional property with a missing key throws keyNotFound.
Paste several records so the generator can see which keys are sometimes absent.