How to use it
- Paste a JSON sample with realistic data; several items per array help find optional keys.
- Choose let (immutable) or var properties.
- Copy the code into a .swift file and decode with
try JSONDecoder().decode(Root.self, from: data).
How it works
The sample is read into a shape: every key with every type seen there. All objects of one array become one struct, so a key present in only some of them becomes optional. Codable decodes a missing optional key as nil.
- Property names are camelCase: order_id → orderId; a Swift keyword such as default is written in backticks.
- Struct names come from keys: items holds [Item], customer becomes Customer.
- A top-level array gives a typealias, such as typealias Root = [RootItem].
Worked example
{"line_items":[{"sku":"A","note":null,"qty":1},{"sku":"B","note":"x"}]} with var gives:
import Foundation
struct Root: Codable {
var lineItems: [LineItem]
enum CodingKeys: String, CodingKey {
case lineItems = "line_items"
}
}
struct LineItem: Codable {
var sku: String
var note: String?
var qty: Int?
}
Tips
- Dates arrive as strings: change the type to Date and set decoder.dateDecodingStrategy (for example .iso8601) if you want them parsed.
- Add Identifiable or Hashable conformance yourself where SwiftUI needs it.
- For Kotlin or TypeScript models of the same JSON, use the neighbouring generators.