logo
GeekFormat

JSON to Swift

Free online JSON to Swift tool. Convert API responses, configuration files, or log JSON into pure Swift struct/class type declarations in one click. No registration, no upload. Real-time generation locally in your browser. Ideal for rapid modeling in iOS, macOS, watchOS, and tvOS projects.

İlgili Öneriler

About JSON to Swift: Turning JSON Data into Apple Ecosystem Native Types

JSON to Swift is the process of automatically converting JSON-formatted data (objects or arrays) into Swift struct/class type declarations. JSON is the de facto standard for REST APIs, configuration files, and event logs, while Swift is the primary development language for iOS, macOS, watchOS, and tvOS apps, and also a core language for server frameworks like Vapor. Developers frequently need to write corresponding Swift types for API-returned JSON; writing by hand is not only time-consuming but also prone to missing optional fields. The purpose of this tool is to automate this process.

This tool uses quicktype-core to complete conversion locally in the browser. quicktype is a multilingual structure generator; this tool enables just-types and no-comments options for Swift, so output is clean struct/class property declarations without serialization annotations like Codable, Decodable, Encodable, and without import statements or file header comments. These "bare types" make it easy for developers to freely add protocols, adjust access control, or change naming conventions preferred by network frameworks like Alamofire/Moya per project needs.

Swift's type system is known for safety. struct is a value type suitable for representing immutable data; class is a reference type suitable for scenarios requiring shared state or inheritance. Properties generated by this tool are mapped to Swift's String, Int, Double, Bool, [T], custom types, etc., as much as possible. After generation, developers can change certain fields to Optional (?), add Codable protocols to types, or upgrade entire structs to classes to get reference semantics per business needs.

Nested object handling is a key capability of the tool. When JSON contains nested objects, the tool recursively generates independent subtypes; for example, if Root contains an address object, an Address type is generated and referenced in the main type via var address: Address. This avoids duplicate type definitions and allows Xcode's autocompletion and type checking to correctly track hierarchical relationships. The naming rule capitalizes the first letter of field names; for example, elements in a users array are named User.

Array type inference follows a "infer from first element" strategy. If array elements are strings, [String] is generated; if integers, [Int]; if floating-point, [Double]; if objects, [CustomType]. Empty arrays [] lack samples and generate [Any] or fallback types; it's recommended to change to concrete types after generation based on actual business. For particularly large or sparse arrays, it's recommended to put real sample elements in the source JSON to improve inference accuracy.

Pure frontend processing is the core architectural advantage of this tool. All JSON parsing and Swift code generation are executed in browser JavaScript (including quicktype-core in Web Worker), not relying on backend services or sending data to any server. This design both protects JSON data that may contain sensitive information and ensures conversion speed is limited only by local device performance without waiting for network roundtrips. It's especially important for processing JSON containing API keys and unreleased business fields.

Unlike some online tools that force-bind Codable/CodingKeys/Date decoding strategies: team members often have different preferences for protocols, naming, and access control. This tool adheres to the minimal output principle, leaving protocol and strategy choices to developers for further processing per project needs. This "generate semi-finished product + project-level secondary processing" workflow is generally more popular with engineers in mid-to-large teams than "one-click all-inclusive."

Kullanım senaryoları

  • iOS development: Convert backend REST API JSON responses to Swift structs for SwiftUI or UIKit network layer modeling and JSONDecoder decoding
  • macOS development: Convert application configuration JSON to Swift types for type-safe configuration reading in AppKit projects, avoiding spelling errors
  • watchOS development: Convert health and exercise data JSON to Swift models for Apple Watch apps and integrate with SwiftUI and HealthKit
  • tvOS development: Convert content recommendation API JSON to Swift types for TV app homepage data display and focus navigation
  • SwiftUI MVVM modeling: Bind API data models directly as @Published properties to ViewModels, then drive interface views
  • Combine reactive data streams: Use JSON response types as Publisher output types with JSONDecoder for reactive parsing
  • SwiftData/Core Data pre-modeling: Generate Swift structs first, then manually add @Model or @NSManaged annotations for entity mapping
  • Third-party SDK integration: Convert JSON response examples from SDK documentation to Swift types for quick integration with login, payment, push, maps, and other SDKs
  • Unit test preparation: Convert interface mock JSON to Swift types for XCTest test data and assertions, improving test maintainability
  • Code review: Convert API response JSON to Swift types for easier discussion of field naming and optionality during team Code Review
  • Flutter/React Native hybrid development: Prepare data models for calling native Swift modules, reducing type conversion errors in the bridge layer
  • Backend interface migration: Generate Swift client models from REST interface documentation or Postman sample JSON for quick synchronization across version upgrades
  • Teaching and training: Demonstrate JSON-to-type-system mapping in Swift/iOS courses to help students understand API data modeling and type safety
  • Health and fitness apps: Convert JSON returned by HealthKit/Fitbit and other interfaces to Swift types for Apple Health data modeling
  • Payment and financial apps: Convert payment gateway interface response JSON to Swift models for easy reconciliation and exception handling
  • E-commerce order systems: Convert order, product, address, and other JSON to Swift structs for display with SwiftUI lists and detail pages
  • News and content apps: Convert CMS JSON responses to Swift types for TableView/SwiftUI lists/detail pages
  • Vapor server development: Convert backend API request/response JSON to Swift structs for server model definitions and Codable encoding/decoding
  • MapKit and geographic data: Convert JSON returned by map interfaces to Swift structs for modeling place search, route planning, and geocoding results

Nasıl Kullanılır

  1. Paste JSON content into the left editor, or click the upload button to select a .json/.txt file, or load built-in sample data
  2. After a 400ms debounce, the tool automatically calls quicktype-core to convert; the right side displays the generated Swift struct/class code
  3. If JSON format is wrong, click the "Fix JSON" button to automatically fix common syntax issues (trailing commas, single quotes, missing quotes, etc.)
  4. Check the generated result; you can manually add protocols like Codable/Equatable/Identifiable per project needs; click "Copy" to paste into Xcode, or click "Download" to save as a .swift file

Özellikler

  • Pure browser-local conversion: JSON parsing and Swift code generation are all completed in the browser via quicktype-core; neither raw JSON nor generated code is uploaded to any server
  • quicktype-core just-types mode: Outputs clean Swift struct/class property declarations without imports, Codable/CodingKeys, or other comments, making it easy to further customize for your project needs
  • 400ms debounced auto-conversion: After pasting or modifying JSON, Swift types are generated almost in real-time without repeatedly clicking the convert button; the conversion process is fully asynchronous and does not block the UI
  • Web Worker background execution: quicktype-core runs in a browser Web Worker, preventing the main thread from freezing and editing lag during large JSON conversions
  • Smart type inference: Automatically maps String, Int, Double, Bool, [T], and custom types; arrays are inferred from the first element type, no manual field typing required
  • Automatic nested object expansion: Recursively generates independent Swift types for each nested object, named by capitalizing the first letter of the field name, avoiding duplicate type definitions
  • Automatic array type inference: JSON arrays are automatically converted to [String]/[Int]/[Double]/[CustomType]; empty arrays default to [Any]
  • One-click JSON error repair: Automatically fix common format errors like trailing commas, single quotes, missing quotes, and comments with one click, then continue converting
  • One-click copy + .swift download: Copy generated Swift code to clipboard in one click, or download as a .swift file to drag directly into your Xcode project
  • Sample data + file upload: Built-in Swift-style sample JSON (with nested address/company/tags), supports drag-and-drop or click upload of .json/.txt files
  • localStorage input history: Automatically saves recent input; quickly resume editing after refresh or accidental page close without worrying about content loss
  • Responsive split-screen editor: Left-right split-screen real-time preview, adaptive for desktop and mobile; smooth operation even on small screens

Kod Örnekleri

Swift: URLSession + JSONDecoder parsing generated struct

swift

Most common usage in iOS/macOS projects: add Codable to structs generated by this tool, then fetch asynchronously with URLSession and decode with JSONDecoder.

import Foundation

// 1) Root type generated by this tool (with Codable protocol added)
struct User: Codable {
    let id: Int
    let name: String
    let email: String
    let isActive: Bool
    let tags: [String]
}

// 2) URLSession async fetch and decode
func fetchUser(id: Int) async throws -> User {
    let url = URL(string: "https://api.example.com/users/\(id)")!
    let (data, response) = try await URLSession.shared.data(from: url)
    guard
        let http = response as? HTTPURLResponse,
        (200..<300).contains(http.statusCode)
    else {
        throw URLError(.badServerResponse)
    }
    return try JSONDecoder().decode(User.self, from: data)
}

// 3) Usage example (Swift 5.5+ async/await)
Task {
    do {
        let user = try await fetchUser(id: 42)
        print("User: \(user.name), tags: \(user.tags)")
    } catch {
        print("Failed to decode:", error)
    }
}

Swift: Alamofire responseDecodable deserializing generated types

swift

When using Alamofire, you can directly use responseDecodable to automatically decode structs generated by this tool into Swift objects.

import Foundation
import Alamofire

// Type generated by this tool, directly usable after adding Codable
struct Product: Codable {
    let id: Int
    let title: String
    let price: Double
    let inStock: Bool
    let images: [String]
}

final class ProductService {
    private let session: Session

    init(session: Session = .default) {
        self.session = session
    }

    /// Alamofire 5 async/await style responseDecodable
    func loadProduct(id: Int) async throws -> Product {
        let url = "https://api.example.com/products/\(id)"
        return try await withCheckedThrowingContinuation { continuation in
            session.request(url)
                .validate(statusCode: 200..<300)
                .responseDecodable(of: Product.self) { response in
                    switch response.result {
                    case .success(let product):
                        continuation.resume(returning: product)
                    case .failure(let error):
                        continuation.resume(throwing: error)
                    }
                }
        }
    }
}

// Moya-style call example
// provider.request(.product(id: 1)).map(Product.self)
// let product: Product = try await provider.request(.product(id: 1)).map(Product.self)

Swift: Combine + JSONDecoder for reactive parsing

swift

In SwiftUI/Combine projects, generated structs can be used with dataTaskPublisher/decode for reactive data streams.

import Foundation
import Combine

// Root type generated by this tool
struct Article: Codable, Identifiable {
    let id: Int
    let title: String
    let body: String
    let publishedAt: Date
}

final class ArticleRepository {
    private let session: URLSession
    private var cancellables = Set<AnyCancellable>()

    init(session: URLSession = .shared) {
        self.session = session
    }

    /// Expose data stream with Combine
    func articlePublisher(id: Int) -> AnyPublisher<Article, Error> {
        let url = URL(string: "https://api.example.com/articles/\(id)")!
        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .iso8601

        return session.dataTaskPublisher(for: url)
            .map(\.data)
            .decode(type: Article.self, decoder: decoder)
            .receive(on: DispatchQueue.main)
            .eraseToAnyPublisher()
    }

    /// Subscribe in SwiftUI ViewModel
    func bind(to viewModel: ArticleViewModel, articleId: Int) {
        articlePublisher(id: articleId)
            .sink(
                receiveCompletion: { completion in
                    if case .failure(let err) = completion {
                        viewModel.errorMessage = err.localizedDescription
                    }
                },
                receiveValue: { article in
                    viewModel.article = article
                }
            )
            .store(in: &cancellables)
    }
}

final class ArticleViewModel: ObservableObject {
    @Published var article: Article?
    @Published var errorMessage: String?
}

Best Practices

Sık Sorulan Sorular

How do I convert JSON to Swift structs?

Paste JSON content into the left input box. After a 400ms debounce, the tool automatically calls quicktype-core to convert to Swift code and displays the result in real time in the right panel. You can also click the upload button to select a .json/.txt file, or click the sample button to load built-in data. After conversion, copy with one click or download as a .swift file.

Does the generated Swift code include Codable?

Not by default. This tool uses quicktype-core's just-types mode, outputting pure struct/class property declarations without Codable, Decodable, or Encodable annotations, and without import statements. If you need Codable, simply add : Codable after generation (e.g., struct User: Codable {}), or write your own JSONDecoder parsing logic.

What JSON data structures are supported?

All valid JSON is supported: basic types (null, boolean, number, string), one-dimensional or multi-dimensional arrays, and nested objects of any depth. The root input can be a JSON object or JSON array; the tool processes objects first and arrays by inferring from the first element. Unsupported inputs include JavaScript special values (functions, Symbol, undefined) and non-JSON text.

How are nested JSON objects handled?

The tool recursively generates independent Swift types for each nested object. Naming rules are based on a combination of parent type name and field name; for example, if Root contains an address field, an Address subtype is generated and referenced in the main type via var address: Address. This avoids duplicate type definitions and allows Xcode's autocompletion and type checking to correctly track hierarchical relationships.

Do array fields get converted to Swift arrays?

Yes. JSON arrays are automatically converted to Swift [T] form. If array elements are strings, [String] is generated; if integers, [Int]; if floating-point, [Double]; if objects, [CustomType]. Empty arrays [] have no sample elements and default to [Any]; it's recommended to manually change to [String] or [Int] or other concrete types after generation.

What type is generated for null value fields?

null values in JSON cannot have their concrete type inferred; the tool may generate Any or a fallback type. It's recommended to replace null-valued fields in the source JSON with sample values (e.g., "field": "" infers String) or manually change to Optional per business logic (e.g., var phone: String?), which better aligns with the safety semantics of Swift's type system.

Can I customize generated struct names?

Yes. Click the type name button (or settings entry) in the toolbar to modify the root type name (default like Root or inferred from sample data). Subtype names are automatically generated based on the root name and field names, with the naming rule being capitalizing the first letter of field names, e.g., users → User, tags → Tag.

What if JSON format is wrong?

The tool automatically checks JSON validity. On error, it displays a specific error message on the right and provides a "Fix JSON" button. Clicking automatically fixes common errors: extra trailing commas, single quotes replaced with double quotes, missing quote key completion, comment removal, etc. After successful repair, you can continue converting without manually fixing JSON.

Is data uploaded to servers? Is it private and secure?

Runs entirely in the local browser. All JSON parsing and Swift code generation are done locally via browser JavaScript (including quicktype-core in Web Worker); input JSON data and generated Swift code are not uploaded to any server, nor recorded or cached to the cloud. Sensitive JSON containing API keys, tokens, user privacy fields, and unreleased business structures can be used safely; closing the page clears everything.

Can generated code be used directly in Xcode projects?

Yes. Generated code is standard Swift syntax that can be directly copied into Xcode .swift files or saved via the "Download" button as a .swift file to drag into projects. Since output is pure type declarations, it's recommended to manually add protocols like Codable, Equatable, Identifiable per project needs, or adjust access control modifiers (public/internal/private).

Are JSON arrays as root input supported?

Yes. When root input is a JSON array, the tool uses the first element of the array as a template to generate the element type and outputs that element type definition. For example, [{"id":1,"name":"A"}] generates a struct named Item (or a name inferred from fields) whose fields are those of the first element; the main type references it via property items: [Item], avoiding treating arrays directly as root types.

Will converting large JSON cause lag?

There's no explicit size limit, but browser parsing and rendering of very large JSON will slow down. Recommendations: ① Convert only one business module's JSON at a time; ② Split deep nesting into levels for processing; ③ For JSON over several MB, use the command-line version of quicktype; ④ Splitting the same JSON into multiple submodules for separate conversion can significantly reduce memory usage.

Can JSON to Swift and JSON to TypeScript be substituted for each other?

Both convert JSON to type definitions for their respective languages, but with different focuses: JSON to Swift generates struct/class property declarations for iOS/macOS native apps; JSON to TypeScript generates interface/type declarations for frontend type checking. If your project has both an iOS client and Web frontend, it's recommended to generate both Swift and TS versions from the same JSON to ensure type consistency across both ends.

How do I add the Codable protocol to generated code?

This tool outputs pure types by default without protocols directly. After generation, you just need to append : Codable after the struct/class declaration, e.g., struct User: Codable {}, for JSONDecoder to use. If you want Codable by default, you can fork quicktype-core and modify its Swift renderer, or use Xcode's batch replace feature to add the protocol to all types after generation.

Is internet required? Can mobile devices use it?

First visit requires internet to fetch tool scripts and quicktype-core resources; afterwards it can run offline from browser cache (in previously visited browsers). Mobile browsers (iOS Safari, Android Chrome) also work normally; the interface has a responsive split-screen design that automatically switches to vertical stacking in portrait mode.

After generation, can I modify individual types without breaking others?

Yes. After generation, each Swift type is an independent struct/class. The tool output is pure text; you can copy individual types into Xcode separately, or use Xcode's Rename refactoring to batch modify types and fields without affecting other types. If you need to regenerate the entire set of types, refresh the page and paste JSON again.

Is Swift enum inference supported?

quicktype's support for unions/enums requires additional type hints or GraphQL/JSON Schema input. Inferring enums from JSON samples alone is difficult, so this tool does not generate enums by default. If you need enums, you can manually change the corresponding struct to enum + Codable, or use the JSON to Kotlin/TypeScript tool first to get enum types, then manually migrate to Swift.

Sorun Giderme

Message says "Please enter JSON data" or right side is empty

Left input box is empty or contains only whitespace. Please paste valid JSON content, or click "Sample" to load an example, or click "Upload" to select a .json/.txt file.

Message says "Unexpected token ... in JSON"

JSON format is invalid. Common causes: ① Trailing comma (e.g., {"a":1,}); ② Using single quotes instead of double quotes; ③ JS object syntax (e.g., {key: value}) instead of JSON (e.g., {"key": "value"}); ④ Contains JavaScript comments. Click the "Fix JSON" button to automatically fix some common errors.

Generated types don't have Codable, can't use JSONDecoder directly

This is expected behavior. This tool uses just-types mode, outputting pure struct/class property declarations. If you need Codable, add : Codable to types after generation (e.g., struct User: Codable {}), or write extension User: Codable {} before calling JSONDecoder.

Empty array [] generated [Any]

Empty arrays have no sample elements; the tool generates fallback type [Any]. It's recommended to put at least one sample element in the source JSON (e.g., [1, 2]), delete the sample value after generation, and manually specify concrete types; or directly change to more precise types like [String]/[User] after generation.

null value field type is uncertain

JSON null cannot have concrete type inferred; the tool may generate Any or fallback types. It's recommended to replace null in source JSON with representative sample values (e.g., "" or 0), then change that field to Optional (?) or concrete type after generation, e.g., var phone: String?.

Generated type names don't match project conventions

You can modify the root type name in the toolbar; subtype names are automatically generated based on root name + field names. If still unsatisfied, use Xcode Rename refactoring to batch modify after generation (right-click → Refactor → Rename); Xcode will synchronously update all references.

Page lags after converting large JSON

Browser rendering of very large JSON and generating many types will slow down. It's recommended to split JSON into multiple independent business modules for separate conversion, or only extract key objects that need modeling for conversion; for JSON over 10MB, we recommend using the command-line version of quicktype.

Xcode compilation error "Type 'X' does not conform to protocol 'Decodable'"

This means after adding Codable to some fields, you didn't correctly handle Optional/Date/Enum and other types. Common fixes: ① Change all fields that may be null to Optional<T>; ② Custom date strategy JSONDecoder().dateDecodingStrategy = .iso8601; ③ Custom CodingKeys to align JSON keys with Swift property names.

Field names are snake_case, Swift convention is camelCase

This tool preserves original JSON field names by default, so snake_case fields are generated as-is. If you want to unify to camelCase, you can batch rename with Xcode Rename after generation, or convert field names to camelCase in a custom quicktype renderer, then add CodingKeys mapping to ensure correct JSON decoding.

Downloaded .swift file shows errors for Chinese keys when opened in Xcode

Swift recommends English ASCII identifiers for field names. If source JSON contains Chinese keys (e.g., {"姓名": "Alice"}), generated var 姓名: String will cause Swift compiler errors in some historical versions. It's recommended to change keys to English in source JSON (e.g., name), which better conforms to Swift coding standards.

Types only have var, no let/private control

This tool generates var public properties by default for easy post-generation customization. If you need let or access control (like private(set)), you can batch modify using Refactor → Add Access Control in Xcode, or replace var with let using sed/text editing tools after generation.

JSON contains ISO 8601 date strings, generated Date fields fail decoding

This tool maps ISO 8601 strings to String by default; Swift does not automatically convert to Date. You need to set dateDecodingStrategy in JSONDecoder, e.g., JSONDecoder().dateDecodingStrategy = .iso8601. If the date format is non-standard, you'll also need to manually implement DateFormatter or custom parsing logic.

Nesting too deep, name conflicts

The tool uses "capitalize first letter of field name" for subtype naming. In deeply nested JSON, nested objects with the same name can cause type conflicts. Solutions: ① Add business prefixes to fields in source JSON; ② Split root JSON into multiple independent modules for separate generation; ③ Use Xcode Rename to batch modify conflicting type names after generation.

Generated public struct but project uses module isolation

This tool generates internal struct by default without explicit public modifier. If your project is split by module and requires cross-module access, you need to batch replace struct with public struct in Xcode, or uniformly add public keyword using sed/awk scripts after generation.

Sözlük

struct
Value type in Swift. Default suitable for representing immutable data models; copied on assignment. This tool generates struct by default for representing JSON objects.
class
Reference type in Swift. Suitable for scenarios requiring shared state, inheritance, or identity (===). This tool can generate class under certain configurations.
Optional (?)
Type modifier in Swift indicating a value may be nil, e.g., var name: String?. Fields generated by this tool are non-Optional by default; ? can be added manually after generation based on whether JSON fields may be missing.
Array ([T])
Shorthand for array type in Swift. This tool converts JSON arrays to [T], where T is inferred from array element types, e.g., [String], [Int], or [CustomType].
Codable
Protocol combination of Decodable and Encodable in Swift. After implementing Codable, JSONDecoder can parse JSON data into type instances. This tool does not generate Codable by default; it must be added manually.
JSONDecoder
JSON parser in the Foundation framework. Used with the Codable protocol to convert Data to Swift type instances. After this tool outputs pure types, developers can parse themselves with JSONDecoder.
URLSession
Network request API in Apple platform Foundation framework. Common usage is URLSession.shared.data(from: url), paired with JSONDecoder to complete API integration.
Alamofire
Most popular third-party HTTP networking library in the Swift community. Wraps URLSession, supports responseDecodable for direct deserialization to Swift types.
Moya
Swift network abstraction layer, typically paired with Alamofire. Moya with Codable types can significantly reduce API call boilerplate code.
Vapor
Mainstream server framework for Swift, building Web applications on macOS/Linux using Swift. Swift structs generated by this tool can also be used for Vapor route models.
quicktype
Open-source multilingual type generator tool; this tool uses quicktype-core in browser Web Worker to complete JSON to Swift conversion.
Property
Property declaration in Swift types. This tool maps each JSON key to a Swift property; for example, "name": "Alice" maps to var name: String.
Type Inference
Process of automatically inferring Swift types from literal forms of JSON values. This tool maps based on null, boolean, number, string, array, object.
localStorage
Browser local key-value storage. This tool uses localStorage to save recent input history; resume after refresh or accidental page close.
Web Worker
Background thread mechanism provided by browsers. This tool loads and executes quicktype-core via Web Worker to prevent large JSON conversions from blocking the main thread.
SwiftUI
Declarative UI framework introduced by Apple. Swift types generated by this tool can serve as data models for SwiftUI views, paired with @State/@ObservedObject to drive interfaces.
Combine
Apple's reactive programming framework. Generated Swift types combined with JSONDecoder can build dataTaskPublisher reactive data streams.
SwiftData
Data persistence framework introduced by Apple in 2023. Types generated by this tool can serve as SwiftData model base classes; after adding @Model, they can be managed by SwiftData.
Value Type / Reference Type
In Swift, struct is value type, class is reference type. This tool generates struct by default, copied on assignment; if reference semantics are needed, manually change to class.
Field Naming
This tool preserves original JSON field names by default. If source JSON is snake_case and the project requires camelCase, manual rename or custom quicktype renderer is needed.
ISO 8601 Date
Common JSON date format, e.g., 2026-07-14T10:00:00Z. Requires JSONDecoder.dateDecodingStrategy = .iso8601 to correctly parse to Date type.

JSON Type to Swift Type Mapping Cheat Sheet

The tool automatically infers corresponding Swift types based on JSON value forms:

JSON Value ExampleDetection MethodGenerated Swift TypeNotes
nullvalue === nullAny? or concrete OptionalCannot infer concrete type; recommend manually changing to Optional<T> after generation
true / falsetypeof value === 'boolean'BoolDirectly maps to Swift boolean type
42typeof value === 'number' && Number.isInteger(value)IntIntegers map to Int (32/64-bit determined by platform)
3.14typeof value === 'number' && !Number.isInteger(value)DoubleFloating point numbers map to Double
"hello"typeof value === 'string'StringStrings map to String
[] (empty array)Array.isArray(value) && value.length === 0[Any]Cannot infer element type; recommend adding examples or manually changing to concrete types
["a", "b"]Array.isArray(value) && typeof value[0] === 'string'[String]String array
[1, 2, 3]Array.isArray(value) && typeof value[0] === 'number'[Int]Integer array
[1.5, 2.5]Array.isArray(value) && typeof value[0] === 'number' && !Number.isInteger(value[0])[Double]Float array
[{...}, {...}]Array.isArray(value) && typeof value[0] === 'object'[Item]Object array, elements are custom types named by field name inference
{...} (nested object)typeof value === 'object' && !Array.isArray(value)Independent struct/classRecursively generates independent types, named by capitalizing first letter of field names

Common Use Cases for JSON to Swift in the Apple Ecosystem

Generated Swift types can be directly used in different scenarios on Apple platforms/third-party frameworks:

Use CaseCommon FrameworksRequired Protocols/ProcessingTypical Code Snippet
REST API parsingURLSession + JSONDecoderAdd Codable to types, maintain struct value semanticstry JSONDecoder().decode(User.self, from: data)
Simplified HTTP requestsAlamofireAdd Codable to types, pair with responseDecodablesession.request(url).responseDecodable(of: User.self)
Abstract network layerMoyaAdd Codable to types, Moya auto-deserializesprovider.request(.user(id: 1)).map(User.self)
Reactive data streamsCombine + JSONDecoderAdd Codable to types, combine with dataTaskPublisherURLSession.shared.dataTaskPublisher(for: url).decode(type: User.self, decoder: decoder)
SwiftUI list displaySwiftUI List + IdentifiableAdd Identifiable to types for automatic List forEachList(items) { Text($0.name) }
Server model definitionsVaporAdd Codable to types, Vapor auto Content serializationstruct User: Codable, Content { var id: Int; var name: String }
Local persistence modelsSwiftData/Core DataAdd @Model/@NSManaged to generated struct/class@Model class User { var id: Int; var name: String }
Cross-platform type sharingJSON to Swift + JSON to TypeScript combinedKeep Swift and TS field names consistent, pair TS types on TS endSwift: var name: String / TS: name: string

Privacy & Security

All JSON parsing and Swift type generation operations of this JSON to Swift tool are completed entirely locally in your browser via JavaScript (quicktype-core/Web Worker). Input JSON data and generated Swift code are never uploaded to any server, nor recorded, cached, or stored in the cloud. Sensitive JSON containing internal interface fields, API keys, tokens, user privacy data, and unreleased business structures can be used safely. All input and output content is automatically cleared from memory when closing or refreshing the page, with no dependency on third-party network services.

Authoritative References