JSON to Swift: Generate Codable Structs from JSON
JSON to Swift on Mac: turn a JSON sample into Codable structs and see how optionals, Int vs Double and CodingKeys are inferred, then test it in Xcode.
GuideUpdated 10 min read
On this page
To convert JSON to Swift Codable structs, paste a sample response into a generator and copy the structs it writes. In Bytepliers, open JSON → Types in the Convert group and paste your JSON into JSON Sample. The Swift output updates as you type, and ⇧⌘C (Shift-Command-C) copies it. If you need other languages or want a free tool for this one job, quicktype also generates Swift.
A generator can only work from the sample you give it. The sections below explain how optionals, number types and CodingKeys are decided, so you know what to check before the code goes into your app.
Write Codable by hand or generate it
Swift's Codable is simple enough that a small model is often quicker to type than to generate. Write it by hand when:
- The payload has only a few fields.
- You need custom decoding, such as string values that should become an enum, dates, default values, or flattening a nested container into one struct. A generator only sees the shape of the data, so it can't know any of that.
Generate it when:
- The payload is large or deeply nested.
- Many
snake_casekeys need CodingKeys. - The response contains arrays of objects whose fields vary from item to item. Spotting every optional by eye is error-prone.
Often the quickest route is to do both. Generate the structs, then edit the few properties that need a real type, such as enums, dates and money.
Convert JSON to Swift structs in Bytepliers
Bytepliers is a Mac app of small offline developer tools. Its JSON → Types tool turns a JSON sample into Swift Codable structs or TypeScript types, and everything runs on your Mac.
- Open Bytepliers and click JSON → Types in the CONVERT group of the sidebar. You can also choose Tools ▸ Convert ▸ JSON → Types, or press ⌘K (Command-K) and search for it.
- Paste your JSON into the JSON Sample pane. You can also drop a
.jsonfile on the pane or use File ▸ Open… (⌘O, Command-O). To see how the tool behaves before using your own data, click Sample in the toolbar. - Keep the Swift tab selected. It's the default.
- Type a name for the top-level struct in Root type. The default is
Root. - Under Properties, choose let (the default) or var.
- Press ⇧⌘C to copy the output, or click Save… (⌘S, Command-S) to save it.


The tool takes input up to 2 MB. Anything larger is refused with a message saying the limit for live conversion is 2 MB.
From any app with the Quick Panel
If the JSON is already on your clipboard, you don't need to open the main window.
- Copy the JSON.
- Press ⌥⌘B (Option-Command-B) to open the Quick Panel.
- Open the Transform menu and choose JSON → Swift Types. Typing a few letters of the transform name also picks it.
- Press ⏎ to copy the result and close the panel.
The panel previews at most 20 KB or 400 lines, but ⏎ copies the full result. This transform has no options, so you can't set a custom root type name or var properties here. Use the tool window for those. The panel refuses clipboard text over 1,000,000 bytes. Press ⌘O in the panel to open the text in the main window instead.
From Terminal with the bytepliers command
Bytepliers includes a command-line tool. Install it from Settings ▸ Integrations ▸ Command-Line Tool ▸ Install…. The bytepliers command-line docs cover the install options.
pbpaste | bytepliers json-to-swift | pbcopyThis command reads JSON from the clipboard, generates Swift types and puts the result back on the clipboard.
The next command overwrites Models.swift if that file already exists.
bytepliers json-to-swift -i response.json > Models.swiftThis command reads response.json and writes the generated Swift to Models.swift.
As part of a saved recipe
Many APIs wrap the part you want in an envelope like { "data": { … } }. In Pipelines, add a jq Filter step with the filter .data, follow it with a JSON → Swift Types step, and save the chain as a recipe. You can then run the recipe on the clipboard from ⌘K, the menu bar or the Quick Panel. The result replaces the clipboard. For details, see pipelines and recipes.
| Method | Root type and let/var | Best for |
|---|---|---|
| JSON → Types window | Yes | Reviewing output and changing options |
| Quick Panel (⌥⌘B) | No | A one-off conversion while you're in Xcode or a browser |
bytepliers json-to-swift | No | Files and shell scripts |
| Pipelines recipe | No | Removing an envelope or filtering before you generate |
How optionals and number types are inferred
The generator reads your sample and applies these rules:
| What the sample contains | What the generated code does |
|---|---|
| A nested object | Makes it a separate named type |
| An array of objects | Creates one element type with a singular name and merges all the elements into it |
| A key that's missing from some array elements | Makes the property optional |
A null value | Makes the property optional |
| Whole numbers in some elements, decimals in others | Uses Double |
| Different kinds of value for the same key, such as a string in one element and a number in another | Uses JSONAny in Swift (a union in TypeScript) |
Merging is what makes arrays come out right. Say one item in a list has "discount": 0.15 and another has no discount key. The property comes out as an optional Double, which is what the decoder needs.
The generator can only see what's in the sample, though:
- A field that's present in every sample but sometimes missing in real responses comes out non-optional. Decoding then fails with
keyNotFound. If you only have one example object, mark such fields optional by hand. - A field that holds whole numbers in every sample gives no sign that it can hold decimals. If it can ever be fractional (prices, ratings, coordinates), change it to
Double. - A field that is
nullin every sample has no type to infer. Check what was generated and set the real type yourself. JSONAnymeans you have a decision to make. Either the API really does return mixed types for that key, which an enum with associated values usually models better, or your sample was edited or inconsistent and you should fix the sample.- Dates. JSON has no date type, so dates arrive as strings or numbers. To get a
Date, change the property type and set the decoder'sdateDecodingStrategy(.iso8601,.secondsSince1970or.millisecondsSince1970). If you can't tell whether an epoch value is in seconds or milliseconds, paste it into the Unix Timestamp tool in Bytepliers. The guide on converting a Unix timestamp on Mac shows how.
So pick a sample whose lists contain varied items, with optional fields present in some and missing in others. The shortest response you can find usually hides the variation that matters.
How CodingKeys and names are handled
By default, synthesized Codable conformance matches property names to JSON keys exactly. Keys like created_at don't follow Swift naming, so the generator writes camelCase property names and adds a CodingKeys enum when a name differs from its key. If a key is a Swift keyword, such as default or class, the generator wraps the property name in backticks.
Here is the standard pattern, written by hand to show the idea. The generator's exact output may differ.
struct User: Codable {
let id: Int
let createdAt: String
enum CodingKeys: String, CodingKey {
case id
case createdAt = "created_at"
}
}Type names come from the structure. Each nested object gets its own type, and array element types get a singularised name. Check these names before you commit. A generic key like data or result can produce a type name that clashes with one already in your project.
Don't combine generated CodingKeys with keyDecodingStrategy = .convertFromSnakeCase. That strategy turns created_at into createdAt before matching, so the key no longer matches the "created_at" raw value in CodingKeys and decoding fails. Leave the decoder on its default key strategy when you use generated code.
Choose let vs var and the root type
Root type names the top-level struct. Root works, but you'll usually want a name like OrdersResponse in a real project. Setting it in the tool saves renaming it later.
Properties sets whether properties are declared with let or var:
- let (the default) suits response models that you decode and then only read. This is the usual choice.
- var suits models you change after decoding, such as data bound to a form or a draft you edit and send back.
If you later add default values by hand, be aware that Swift never decodes a let property that has an initial value, and it warns you about it. Switch those properties to var. Even then, synthesized decoding still requires the key to be present: the default isn't used when the key is missing.
The same tool also generates TypeScript. Switch to the TypeScript tab and set Declare as to interface (the default) or type.
Bytepliers vs quicktype
We make Bytepliers, so weigh this section accordingly. quicktype is a dedicated generator of typed models from JSON, and its web app and command-line tool are free and open source. Prices and details below are as of November 2026.
| Bytepliers JSON → Types | quicktype | |
|---|---|---|
| Output languages | Swift and TypeScript only | C#, Swift, TypeScript, Go, C++, Kotlin, Objective-C and more |
| Input | A JSON sample | Sample JSON, JSON Schema or GraphQL |
| Where it runs | Native Mac app, offline, plus Quick Panel, CLI and recipes | Web app (the company says it works offline), CLI (needs Node.js 20 or later from v24), extensions for VS Code, Visual Studio and Xcode |
| Price | Included with MacSuite: $349 one-time for every MacSuite app, 7-day free trial | Web app and CLI are free and open source |
| Scope | 40 other tools, including JSON Formatter with jq, cURL → Code and JWT Decoder | Type and model generation only |
Pick quicktype if you need languages other than Swift and TypeScript, want to generate from JSON Schema or GraphQL, or only need this one job and want it free. Its Xcode extension adds Editor ▸ quicktype ▸ Paste JSON as Code. The Mac App Store listing for it looks old (around 2017–2018), so check that it still works with your version of Xcode.
Pick Bytepliers if you already use it, or if you want type generation next to the other tools you use on the same payloads. Those include repairing broken JSON, filtering it with jq, fetching a live response, and turning the request into code with cURL → Code.
Check the result in Xcode
Generated models should be tested against real data before you rely on them.
- In Xcode, create a new Swift file, for example
Models.swift, and paste the generated code. - Build with ⌘B (Command-B) to catch name clashes.
- In a unit test or a playground, decode the same sample you generated from:
import Foundation
let json = """
{ "id": 1, "created_at": "2026-11-11T10:00:00Z" }
"""
do {
let root = try JSONDecoder().decode(Root.self, from: Data(json.utf8))
print(root)
} catch {
print(error)
}- Decode a few other real responses as well, especially ones with empty lists, missing fields or
nullvalues.
The printed error tells you what to fix:
| Error | Usual cause | Fix |
|---|---|---|
keyNotFound | A field missing from this response was non-optional | Make the property optional |
valueNotFound | A field was null but the property is non-optional | Make the property optional |
typeMismatch | A value arrived as a different kind, such as a number sent as a string | Change the property type or decode that value by hand |
dataCorrupted | The JSON is invalid, a decimal arrived in an Int property, or a date doesn't match dateDecodingStrategy | Validate the JSON, change Int to Double, or fix the date strategy |
If it doesn't work
- JSON → Types shows an error instead of Swift. The sample may not be strict JSON, for example if it has comments, trailing commas, single quotes or
undefined. Paste it into JSON Formatter first. Its default Lenient mode repairs these problems, reports "Repaired N issues" and outputs strict JSON that you can copy into JSON → Types. The guide on formatting JSON on Mac covers this. - The input is over 2 MB. You don't need the whole file. In JSON Formatter's filter bar, the jq filter
[limit(500; .[])]keeps the first 500 items of a top-level array. Keep enough items to capture the variation between them. - There's a wrapper type you don't want. The response has an envelope like
{ "data": … }. Filter it with.datain JSON Formatter's jq bar, or build the jq-and-Swift recipe described above. - The Quick Panel says the clipboard is too large. The panel refuses clipboard text over 1,000,000 bytes. Use the JSON → Types window, which accepts up to 2 MB.
- Decoding fails only when you use
convertFromSnakeCase. Remove that strategy. The generated CodingKeys already map the names. - The shell says
command not found: bytepliers. If you installed the command in~/.local/bin, add that folder to your shell's PATH, or reinstall in/usr/local/binfrom Settings. If the command says "Open Bytepliers once to enable the command-line tool.", open the app once and try again.
FAQ
Does my JSON leave my Mac? No. The tools run offline. Bytepliers does keep your inputs in a local per-tool history at ~/Library/Application Support/Bytepliers/history.json. If you don't want API data stored there, go to Settings ▸ History and turn off Remember recent inputs per tool and Restore each tool's last input at launch, or use Clear All History….
Can it generate Kotlin, Go or C# models? No. JSON → Types outputs only Swift and TypeScript. quicktype covers those languages for free.
Can I run JSON → Swift Types from the Shortcuts app? No. Bytepliers' Transform Text action doesn't include this transform. Use the Quick Panel or the CLI instead, or a bytepliers://run/jsonToSwift link, which asks before it touches your clipboard. The bytepliers:// links docs explain the options.
For every other tool and its options, see the Bytepliers tool reference. Bytepliers is part of MacSuite, and every tool works during the 7-day free trial.