JSON to Swift Struct

Generate Codable Swift structs from JSON with automatic CodingKeys for snake_case keys.

snake_case keys are automatically converted to camelCase with CodingKeys mapping.

What is Swift Codable?

Codable is Swift's built-in protocol for encoding and decoding data. A struct or class that conforms to Codable (which combines Encodable and Decodable) can be serialized to JSON and deserialized from JSON using JSONEncoder and JSONDecoder, both part of the Foundation framework.

Codable is the standard for API calls in iOS, macOS, watchOS, and tvOS apps — and in server-side Swift with Vapor or Hummingbird. Writing Codable structs by hand for complex JSON responses is slow and error-prone. This tool generates all the structs from your JSON, complete with CodingKeys enums for snake_case-to-camelCase mapping.

JSON to Swift Codable Example

Input JSON from an API:

json
{
  "user_id": 42,
  "display_name": "Alice",
  "is_premium": true,
  "account": { "plan": "pro", "expires_at": "2026-12-01" }
}

Generated Swift structs:

swift
import Foundation

struct Account: Codable {
    let plan: String
    let expiresAt: String

    enum CodingKeys: String, CodingKey {
        case plan
        case expiresAt = "expires_at"
    }
}

struct Root: Codable {
    let userId: Int
    let displayName: String
    let isPremium: Bool
    let account: Account

    enum CodingKeys: String, CodingKey {
        case userId = "user_id"
        case displayName = "display_name"
        case isPremium = "is_premium"
        case account
    }
}

Decode with URLSession

swift
let (data, _) = try await URLSession.shared.data(from: url)
let root = try JSONDecoder().decode(Root.self, from: data)

Or use a custom decoder: let decoder = JSONDecoder(); decoder.keyDecodingStrategy = .convertFromSnakeCase — but manual CodingKeys gives you more control.

Type Mapping

JSON TypeSwift TypeNotes
stringStringNon-optional
integerIntPlatform-native size
floatDoubleDouble precision
booleanBooltrue / false
nullAny?Optional Any
array[T]Array literal syntax
objectstructNew named Codable struct
snake_case keyCodingKeys enumAuto-generated mapping

Frequently Asked Questions

CodingKeys is added only when at least one JSON key name differs from the camelCase Swift property name. Pure camelCase JSON produces simpler structs.

Yes — make the struct a class conforming to ObservableObject, or wrap it in an @State / @Published property. The Codable conformance is independent of SwiftUI binding.

Change let propertyName: Type to let propertyName: Type? after generation. Optional properties are skipped when missing without throwing an error.

Yes — use AF.request(url).responseDecodable(of: Root.self) { response in ... }. Alamofire uses JSONDecoder internally so your Codable structs work directly.

Dates are generated as String. Set decoder.dateDecodingStrategy = .iso8601 and change the property type to Date to parse ISO 8601 strings automatically.

Related Tools