JSON to Swift Codable

Generate Swift structs conforming to the Codable protocol from JSON data. Supports CodingKeys for snake_case mapping and Identifiable conformance.

Input JSON
Swift Struct Output

Features

🍎 Codable Protocol

  • Encodable & Decodable
  • Nested struct generation
  • Proper Swift type mapping
  • Foundation import included

🔑 CodingKeys Support

  • Auto snake_case to camelCase
  • CodingKeys enum generated
  • Maps JSON keys correctly
  • Optional key customization

⚡ Smart Type Detection

  • Int vs Double inference
  • Bool, String, optional types
  • Array type [T] generation
  • Identifiable conformance option

Swift Codable Guide

Swift Codable Protocol

Codable is Swift's type-safe serialization protocol. It combines Encodable and Decodable, enabling you to convert between Swift types and JSON with minimal code.

import Foundation

struct User: Codable {
    let id: Int
    let name: String
    let isActive: Bool

    enum CodingKeys: String, CodingKey {
        case id
        case name
        case isActive = "is_active"
    }
}

Decoding JSON reliably with Codable

Codable turns JSON into Swift types with very little code. The catch is that a single mismatched field makes the whole decode fail, so it helps to plan for the variations real APIs produce.

Tips and common pitfalls

  • Set decoder.keyDecodingStrategy = .convertFromSnakeCase to map user_name to userName without writing CodingKeys.
  • Use optionals for any field the server may omit or send as null.
  • Set decoder.dateDecodingStrategy = .iso8601 when timestamps are ISO 8601 strings.
  • When decoding fails, print the DecodingError; its context names the exact key path that did not match.

More questions

Should models be structs or classes?

Prefer structs. They are value types, thread-safe to pass around and work naturally with SwiftUI. Use classes only when you need shared mutable identity.

How do I decode an array at the top level?

Decode the array type directly: try JSONDecoder().decode([User].self, from: data).