Output will appear here
Output will appear here
Paste JSON and this tool writes Swift structs that conform to Codable, ready for JSONDecoder().decode(Root.self, from: data). snake_case keys become camelCase properties with a CodingKeys enum. Nulls and keys missing from some array elements become optionals. ISO 8601 timestamps become Date, so set decoder.dateDecodingStrategy = .iso8601.
By Ankit Aglawe · Updated · Runs entirely in your browser
Only structs with a renamed key get a CodingKeys enum, so Coord and WeatherItem stay short. alerts is null in the only sample, so its type is unknown and it becomes JSONAny?; the JSONAny helper is appended because Swift's Any is not Codable. Replace it with the real type once you have a sample with alerts.
{
"name": "Lisbon",
"timezone_offset": 3600,
"coord": { "lat": 38.7167, "lon": -9.1333 },
"current": {
"temp": 21.4,
"feels_like": 21.1,
"humidity": 64,
"weather": [{ "id": 801, "main": "Clouds", "description": "few clouds", "icon": "02d" }]
},
"alerts": null
}struct Coord: Codable {
let lat: Double
let lon: Double
}
struct WeatherItem: Codable {
let id: Int
let main: String
let description: String
let icon: String
}
struct Current: Codable {
let temp: Double
let feelsLike: Double
let humidity: Int
let weather: [WeatherItem]
enum CodingKeys: String, CodingKey {
case temp
case feelsLike = "feels_like"
case humidity
case weather
}
}
struct Root: Codable {
let name: String
let timezoneOffset: Int
let coord: Coord
let current: Current
let alerts: JSONAny?
enum CodingKeys: String, CodingKey {
case name
case timezoneOffset = "timezone_offset"
case coord
case current
case alerts
}
}
/// A JSON value whose type varies across samples. `Any` is not `Codable`,
/// so heterogeneous fields need a concrete conforming type.
struct JSONAny: Codable {
let value: Any?
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if container.decodeNil() {
value = nil
} else if let v = try? container.decode(Bool.self) {
value = v
} else if let v = try? container.decode(Int.self) {
value = v
} else if let v = try? container.decode(Double.self) {
value = v
} else if let v = try? container.decode(String.self) {
value = v
} else if let v = try? container.decode([JSONAny].self) {
value = v
} else if let v = try? container.decode([String: JSONAny].self) {
value = v
} else {
value = nil
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch value {
case let v as Bool: try container.encode(v)
case let v as Int: try container.encode(v)
case let v as Double: try container.encode(v)
case let v as String: try container.encode(v)
case let v as [JSONAny]: try container.encode(v)
case let v as [String: JSONAny]: try container.encode(v)
default: try container.encodeNil()
}
}
}The keys are already camelCase, so no CodingKeys is needed. releaseDate becomes Date and import Foundation is added. isStreamable is missing from one track, so it is Bool?. trackPrice is -1 in one row and 1.29 in the others, so it widens to Double.
[
{ "trackId": 1440833098, "trackName": "Blinding Lights", "artistName": "The Weeknd", "trackPrice": 1.29, "releaseDate": "2019-11-29T12:00:00Z", "isStreamable": true },
{ "trackId": 1544494392, "trackName": "Levitating", "artistName": "Dua Lipa", "trackPrice": 1.29, "releaseDate": "2020-03-27T12:00:00Z" },
{ "trackId": 1622045624, "trackName": "As It Was", "artistName": "Harry Styles", "trackPrice": -1, "releaseDate": "2022-04-01T12:00:00Z", "isStreamable": false }
]import Foundation
struct Root: Codable {
let trackId: Int
let trackName: String
let artistName: String
let trackPrice: Double
let releaseDate: Date
let isStreamable: Bool?
}
typealias RootArray = [Root]Every code generator on this site is run on the same awkward input: a 64-bit id, a float written as 1.0, a null, a date string, a reserved word as a key, an empty array, a nested array and an array of objects whose keys differ. This is the exact output for Swift, generated when the page was built.
{
"id": 9007199254740993,
"price": 19.99,
"ratio": 1.0,
"deleted_at": null,
"created_at": "2024-01-15T10:30:00Z",
"class": "premium",
"tags": [],
"matrix": [[1, 2], [3, 4.5]],
"items": [{ "sku": "A1", "qty": 1 }, { "sku": "B2", "qty": 2, "note": "gift" }]
}import Foundation
struct Item: Codable {
let sku: String
let qty: Int
let note: String?
}
struct Root: Codable {
let id: Int
let price: Double
let ratio: Int
let deletedAt: JSONAny?
let createdAt: Date
let `class`: String
let tags: [JSONAny]
let matrix: [[Double]]
let items: [Item]
enum CodingKeys: String, CodingKey {
case id
case price
case ratio
case deletedAt = "deleted_at"
case createdAt = "created_at"
case `class`
case tags
case matrix
case items
}
}
/// A JSON value whose type varies across samples. `Any` is not `Codable`,
/// so heterogeneous fields need a concrete conforming type.
struct JSONAny: Codable {
let value: Any?
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if container.decodeNil() {
value = nil
} else if let v = try? container.decode(Bool.self) {
value = v
} else if let v = try? container.decode(Int.self) {
value = v
} else if let v = try? container.decode(Double.self) {
value = v
} else if let v = try? container.decode(String.self) {
value = v
} else if let v = try? container.decode([JSONAny].self) {
value = v
} else if let v = try? container.decode([String: JSONAny].self) {
value = v
} else {
value = nil
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch value {
case let v as Bool: try container.encode(v)
case let v as Int: try container.encode(v)
case let v as Double: try container.encode(v)
case let v as String: try container.encode(v)
case let v as [JSONAny]: try container.encode(v)
case let v as [String: JSONAny]: try container.encode(v)
default: try container.encodeNil()
}
}
}Both become optionals. Swift's synthesized Codable decodes a missing key into an optional as nil, so let note: String? works whether the key is absent or null. In the edge-case output, note is optional because one item lacks it.
With no non-null sample there is no type to infer, so deleted_at becomes JSONAny?. JSONAny is a small Codable wrapper emitted at the bottom of the file only when something uses it. Swap it for Date? or String? when you know the real type.
Whole numbers become Int, which is 64 bits on every current Apple platform, so 9007199254740993 decodes exactly. Numbers with a fraction become Double. 1.0 arrives as 1 after browser parsing, so ratio comes out Int; change it to Double if it can hold fractions.
A key like class, default or protocol stays the property name, wrapped in backticks (Swift's own escape for identifiers). The escaped name is used in CodingKeys too, so no rename is needed. Keys that start with a digit get a field prefix and a CodingKeys mapping back to the original.
2024-01-15T10:30:00Z becomes Date. JSONDecoder defaults to .deferredToDate, which expects a number, so decoding fails with "Expected to decode Double but found a string" until you set decoder.dateDecodingStrategy = .iso8601. That strategy does not accept fractional seconds, so for values like 2024-01-15T10:30:00.123Z use a .custom strategy with an ISO8601DateFormatter that has .withFractionalSeconds set. Date-only strings like 2024-01-15 stay String.
Nested arrays become [[Double]], with all inner values merged, so one 4.5 makes the matrix Double. An empty array has no element type and becomes [JSONAny].
| JSON value | Swift type | Notes |
|---|---|---|
| string | String | |
| ISO 8601 date-time string | Date | Needs .iso8601 decoding strategy |
| integer | Int | 64-bit on Apple platforms |
| number with a fraction | Double | |
| true / false | Bool | |
| null or key missing in some objects | T? | |
| only ever null | JSONAny? | Helper struct is emitted |
| object | struct Name: Codable | Named after its key, PascalCase |
| array | [T] | All elements merged |
| mixed types or empty array | JSONAny / [JSONAny] |
Paste a JSON object or array into the editor. The converter accepts any valid JSON including arrays of heterogeneous objects and deeply nested structures.
The output pane shows Swift structs conforming to the Codable protocol. Each struct includes stored properties with correct Swift types and a CodingKeys enum when JSON keys differ from Swift naming conventions.
Copy the generated code into a .swift file in your project. Decode JSON data using JSONDecoder().decode(Root.self, from: data) with no additional configuration needed.
Paste the JSON on the left and copy the structs on the right into a .swift file. Then decode with try JSONDecoder().decode(Root.self, from: data), or [Root].self when the JSON is a top-level array.
Only when at least one property name differs from its JSON key, such as feels_like becoming feelsLike. Structs whose keys are already valid camelCase get no CodingKeys enum at all.
You can, but explicit CodingKeys keep each mapping visible and also handle keys that the strategy gets wrong, like ones starting with digits. Do not combine the two, or the strategy converts the key before your CodingKeys raw value is matched.
Timestamp fields are typed Date, and JSONDecoder expects dates as numbers by default. Set decoder.dateDecodingStrategy = .iso8601 before decoding.
They are let, so the structs are immutable value types. Change them to var if you need to edit a decoded value in place, for example in a SwiftUI form.
Yes. Fetch with let (data, _) = try await URLSession.shared.data(from: url) and decode into the generated type. Add Identifiable yourself if you want to use the array directly in a List.
Need several formats at once? Convert All shows every output from one paste. Or browse all JSON converters.