Home › Developer Tools › JSON to Swift Struct

JSON to Swift Struct

Paste a JSON object or API response and get ready-to-use Swift Codable structs with camelCase properties, CodingKeys, optionals and nested types. Everything runs in your browser.

Last updated:

Your JSON is parsed locally in this tab and never uploaded. Tip: Ctrl + Enter generates.

Advertisement
Advertisement

How to use the JSON to Swift Struct

  1. Paste your JSON into the left box, or open a .json file. A sample is loaded so you can see the output right away.
  2. Name the root struct, for example User or APIResponse.
  3. Choose how property names are made: camelCase with CodingKeys, names for .convertFromSnakeCase, or the JSON keys as they are.
  4. Set optionals, protocols and style: Codable or Decodable, let or var, public access, nested types, Date parsing.
  5. Press Generate Swift Structs, then copy the code or download the .swift file and decode with JSONDecoder.

Example: JSON to Swift Codable structs

This API response has snake_case keys, a date, a nested array of objects and a field that is missing from one item:

{ "user_id": 42, "display_name": "Ada", "joined_at": "2024-05-01T09:30:00Z",
  "posts": [ { "id": 1, "title": "Hello", "score": 4.5 },
             { "id": 2, "title": "Draft", "score": 3, "cover_url": "a.png" } ] }

With the default options the generator produces:

struct Root: Codable {
    let userID: Int
    let displayName: String
    let joinedAt: Date
    let posts: [Post]

    enum CodingKeys: String, CodingKey {
        case userID = "user_id"
        case displayName = "display_name"
        case joinedAt = "joined_at"
        case posts
    }
}

struct Post: Codable {
    let id: Int
    let title: String
    let score: Double
    let coverURL: String?

    enum CodingKeys: String, CodingKey {
        case id, title, score
        case coverURL = "cover_url"
    }
}

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let root = try decoder.decode(Root.self, from: jsonData)

coverURL is optional because only one post has it, and score is Double because one value is 4.5.

How JSON values map to Swift types

JSON valueSwift type
"text"String
"2024-05-01T09:30:00Z"Date (with .iso8601, when the option is on)
42Int
3.14, 1e6Double
true / falseBool
"x" or null, or a missing keyString?
{ … }A nested struct
{}[String: JSONValue]
[1, 2] / [][Int] / [JSONValue]
[1, "two"] or always nullJSONValue

CodingKeys or convertFromSnakeCase?

Both approaches decode the same snake_case JSON. Explicit CodingKeys keep the mapping visible in the type, let you use Swift initialisms such as userID and coverURL, and work no matter how the decoder is configured. .convertFromSnakeCase keeps the structs shorter, but the property names must match its conversion exactly (user_id becomes userId), and every decoder that reads the type must set the strategy. Pick the matching option above and the generator names the properties for you.

  • Unknown keys are ignored by JSONDecoder, so you can delete properties you do not need.
  • A missing non-optional key throws DecodingError.keyNotFound; make the property optional if the API sometimes omits it.
  • Identifiable: structs with an id property can adopt Identifiable for SwiftUI lists by adding it to the protocol list.

Frequently asked questions

When does the generator add a CodingKeys enum?

Swift's synthesized Codable matches property names to JSON keys exactly. When a property name differs from its key (for example userName for user_name), the struct needs a CodingKeys enum that maps every property to its key. The generator adds CodingKeys only to structs that need it and lists all of that struct's properties, because a CodingKeys enum must cover every stored property that is decoded.

What does the convertFromSnakeCase option do?

JSONDecoder can convert snake_case keys for you with decoder.keyDecodingStrategy = .convertFromSnakeCase. It removes underscores, lower-cases the first word and capitalises the following words, so avatar_url becomes avatarUrl (not avatarURL). This mode names properties exactly as that strategy produces them, so no CodingKeys are needed except for keys with characters such as dashes.

Which properties become optionals?

By default a property is optional (String?) when its value is null somewhere in the JSON or when the key is missing from some items of an array. Synthesized Codable decodes optionals with decodeIfPresent, so a missing key or null becomes nil instead of throwing an error. You can also make every property optional, which is safest for APIs you do not control.

How are dates handled?

Strings in the ISO 8601 internet date-time format, such as 2024-05-01T09:30:00Z, become Date when the option is on. Set decoder.dateDecodingStrategy = .iso8601 so JSONDecoder can read them. That strategy does not accept fractional seconds, so timestamps like 2024-05-01T09:30:00.123Z stay String; turn the option off to keep all dates as strings.

What is the JSONValue enum?

Swift has no Codable equivalent of Any, so a field whose type cannot be known (always null, mixed strings and numbers, or an empty object) uses a small JSONValue enum that is generated at the end of the code. It decodes any JSON value into cases such as .string, .number, .bool, .array, .object and .null and encodes it back.

How are numbers typed?

Whole numbers become Int, which is 64-bit on all current Apple platforms, and numbers with a decimal point or exponent become Double. If a field mixes whole and decimal numbers, Double is used.

Is my JSON uploaded?

No. Parsing and code generation are plain JavaScript running in this page, so API responses with personal or secret data never leave your device.

Are all the tools on FreeToolCabin tested for quality and accuracy?

Yes! Every tool on our site undergoes automated Q/A testing in real browser environments to ensure high precision, correct output, and zero errors. If you happen to spot a bug or have a suggestion, please contact us at [email protected] and our team will review it right away.

Related tools

JSON to Kotlin Data ClassTurn JSON into Kotlin data classes for kotlinx.serialization, Gson, Moshi or Jackson.JSON to TypeScriptGenerate TypeScript interfaces or types from JSON, with nested types and optional fields.JSON to Go StructTurn JSON into Go structs with inferred types, nested structs and json tags.JSON FormatterBeautify, minify and validate JSON, with a collapsible tree view.JSON to Excel ConverterTurn JSON into a styled .xlsx spreadsheet; nested arrays become their own linked sheets.JSON to CSVConvert JSON data to CSV for spreadsheets.CSV to JSONConvert CSV data to JSON with live preview.Excel to CSVConvert XLSX spreadsheets to CSV.CSV ViewerOpen a CSV or TSV file as a sortable, filterable table.Excel Viewer (XLSX / XLS)Open XLSX, XLS and ODS spreadsheets in your browser without Excel.Line Ending ConverterConvert text and files between CRLF, LF and CR line endings.Markdown to HTMLConvert Markdown to clean HTML with a live editor.XML to JSONConvert XML to JSON with validation.Text Encoding ConverterDetect and convert text file encodings like UTF-8, UTF-16 and Latin-1.JSON ViewerExplore JSON as a collapsible tree, search keys and values and copy any node's path.TTF to WOFF2 ConverterConvert TTF and OTF fonts to WOFF2 or WOFF and get a ready @font-face CSS snippet.Chmod CalculatorConvert Linux file permissions between checkboxes, octal (755) and symbolic (rwxr-xr-x) notation.Morse Code TranslatorTranslate text to Morse code and back, then play it as sound or a blinking light, or save a WAV.HTML Table GeneratorBuild HTML tables in an editable grid with styles, header rows, CSV import and live preview.Hex to Text ConverterConvert hex to text and text to hex with UTF-8 support and space, 0x, \x or comma formats.JSON to XML ConverterConvert JSON to well-formed XML with attributes, arrays and pretty print.JSON to YAML ConverterConvert JSON to clean YAML as you type, with indent, quoting and sort options.YAML to JSON ConverterConvert YAML to pretty or minified JSON, with errors pinned to the exact line.HTML to Markdown ConverterTurn HTML or pasted rich text into clean Markdown with tables and live preview.Markdown Table GeneratorBuild Markdown tables in a grid or paste from Excel/CSV, with alignment and preview.JSON ValidatorCheck JSON with the exact line and column of each error, fix tips and one-click auto-fix.Image to Base64Convert images to Base64 data URIs, CSS backgrounds and HTML img tags in your browser.Base64 to ImagePaste a Base64 string or data URI to preview, identify and download the image.JSON CompareCompare two JSON documents and see every added, removed and changed path.Hex to DecimalConvert hex to decimal instantly with steps and signed mode.Decimal to HexConvert decimal to hex instantly with steps and signed mode.Binary to DecimalConvert binary to decimal instantly with steps and signed mode.Decimal to BinaryConvert decimal to binary instantly with steps and signed mode.Two's Complement CalculatorDecimal to two's complement binary and back for 4-64 bits, with invert-and-add-1 steps.XML to CSV ConverterConvert XML to CSV: detects repeating records, flattens nested data, pick your columns.CSV to XML ConverterConvert CSV to well-formed XML with custom root and row names, escaping and pretty print.TOML to JSON ConverterConvert TOML to JSON and JSON to TOML with a full v1.0 parser and clear error lines.JSON to Python ClassGenerate Python dataclasses, Pydantic models or TypedDicts with type hints from JSON.CSV Diff CheckerCompare two CSV files by key column and see added, removed and changed rows cell by cell.CSV Duplicate Row RemoverRemove duplicate rows from a CSV by all or selected columns and download the cleaned file.CSV to HTML TableTurn CSV into clean HTML table code with a live preview, styling options and one-click copy.CSV to Markdown TableConvert CSV to a neatly aligned GitHub Markdown table with column alignment and live preview.CSV TransposeSwap rows and columns of CSV, TSV or pasted spreadsheet data, with delimiter auto-detect.Date Format ConverterConvert any date to ISO 8601, RFC 2822, Unix time and custom strftime, moment or Java patterns.ENV to JSON ConverterConvert .env files to JSON or YAML and JSON back to .env, with quotes and multiline values.File to Base64Convert any file to a Base64 string or data URI with MIME detection, line wrap and download.HTML Table to CSVExtract any table from HTML or page source to CSV, TSV or JSON, with colspan and rowspan handled.IEEE 754 Floating Point ConverterConvert decimals to 32/64-bit IEEE 754 floats: toggle bits, see hex, exact value and rounding error.INI to JSON ConverterConvert INI and CFG files to JSON and JSON back to INI, with sections, arrays and types.IP Address ConverterConvert IPv4 to decimal, hex, binary, octal and back, with class and private/public check.ISBN Converter & ValidatorConvert ISBN-10 to ISBN-13 and back, validate check digits and hyphenate, one or in bulk.JSON Flatten / UnflattenFlatten nested JSON to dot or bracket path keys, or unflatten flat keys back to nested JSON.JSON to Dart ClassTurn JSON into Dart model classes with fromJson, toJson, null safety and nested classes.JSON to Java ClassTurn JSON into Java POJOs or records with Lombok, getters/setters and Jackson or Gson annotations.JSON to Markdown TableTurn a JSON array of objects into a GitHub Markdown table with column picker and alignment.JSON to PHP ArrayConvert JSON to PHP array code (short [] or array()) and PHP arrays back to JSON.JSON to Rust StructTurn JSON into Rust structs with serde derives, rename attributes, Option and Vec types.JSON to SQL ConverterConvert a JSON array of objects to CREATE TABLE and INSERT statements for MySQL, Postgres, SQLite.JSON to TOML ConverterConvert JSON to clean TOML with tables, arrays of tables, inline tables and dates.JSONL to JSON ConverterConvert JSON Lines / NDJSON to a JSON array and back, with line-level error reports.Properties to YAML ConverterConvert Java .properties to nested YAML (application.yml) and YAML back to properties.PX to EM ConverterConvert pixels to em using the parent font size, and em back to px, with conversion tables.Query String to JSONConvert URL query strings to JSON with nested brackets and arrays, and JSON back to a query string.REM to PX ConverterConvert CSS rem values to pixels for any root font size, with a quick 0.25–6rem table.SQL to JSON ConverterConvert SQL INSERT statements and dumps into a JSON array of row objects, with CSV export.TSV to CSV ConverterConvert TSV to CSV and back, or between tab, comma, semicolon and pipe, with correct quoting.TypeScript to JavaScriptConvert TypeScript or TSX to clean JavaScript instantly: strip types, keep or compile JSX.XML to YAML ConverterConvert XML to clean YAML with attributes, text nodes, lists and exact error lines.
See all 129 Data & File Format Converters →