JSON to Swift Struct
Generate Codable Swift structs from JSON with automatic CodingKeys for snake_case keys.
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:
{
"user_id": 42,
"display_name": "Alice",
"is_premium": true,
"account": { "plan": "pro", "expires_at": "2026-12-01" }
}Generated Swift structs:
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
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 Type | Swift Type | Notes |
|---|---|---|
| string | String | Non-optional |
| integer | Int | Platform-native size |
| float | Double | Double precision |
| boolean | Bool | true / false |
| null | Any? | Optional Any |
| array | [T] | Array literal syntax |
| object | struct | New named Codable struct |
| snake_case key | CodingKeys enum | Auto-generated mapping |