logo
GeekFormat

JSON a Swift

Herramienta online gratuita de JSON a Swift. Convierte respuestas API, archivos de configuración o JSON de registro en declaraciones de tipo struct/class Swift puras con un clic. Sin registro ni subida. Generación en tiempo real en tu navegador. Ideal para modelado rápido en proyectos iOS, macOS, watchOS y tvOS.

Relacionado

Acerca de JSON a Swift: Convirtiendo datos JSON en tipos nativos del ecosistema Apple

JSON a Swift es el proceso de convertir automáticamente datos JSON (objetos o arrays) en declaraciones de tipo struct/class Swift. JSON es el estándar de facto para APIs REST, archivos de configuración y registros, mientras que Swift es el lenguaje principal para iOS, macOS, watchOS y tvOS, además de Vapor. Escribir tipos Swift manualmente para JSON de API consume tiempo y es propenso a errores; esta herramienta automatiza el proceso.

Esta herramienta usa quicktype-core en el navegador para la conversión. quicktype es un generador de estructuras multilingüe; habilitamos las opciones just-types y no-comments para Swift, generando declaraciones limpias sin anotaciones de serialización ni imports. Estos "tipos desnudos" permiten a los desarrolladores añadir protocolos y ajustar el control de acceso libremente.

El sistema de tipos de Swift es conocido por su seguridad. struct es tipo por valor para datos inmutables; class es tipo por referencia para estado compartido o herencia. Las propiedades se mapean a String, Int, Double, Bool, [T], tipos personalizados. Los desarrolladores pueden cambiar campos a Optional (?) o añadir Codable según necesidades.

El manejo de objetos anidados es clave. Se generan subtipos independientes recursivamente (ej., address → Address referenciado como var address: Address). La nomenclatura capitaliza la primera letra de los campos (users → User).

La inferencia de arrays sigue la estrategia "inferir del primer elemento". Arrays vacíos generan [Any]; se recomienda cambiar a tipos concretos. Para arrays grandes o dispersos, poner elementos de muestra reales mejora la precisión.

El procesamiento frontend puro es la ventaja arquitectónica clave. Todo se ejecuta en JavaScript (quicktype-core en Web Worker) sin enviar datos a servidores, protegiendo JSON sensible y garantizando velocidad sin latencia de red.

A diferencia de herramientas que fuerzan Codable/CodingKeys, esta herramienta se adhiere al principio de salida mínima, dejando decisiones de protocolo y estrategia a los desarrolladores. Este flujo de trabajo es popular en equipos medianos y grandes.

Casos de uso

  • Desarrollo iOS: Convertir JSON de API REST a structs Swift para modelado de red y decodificación JSONDecoder
  • Desarrollo macOS: Convertir JSON de configuración a tipos Swift para lectura con seguridad de tipos en AppKit
  • Desarrollo watchOS: Convertir datos de salud y ejercicio a modelos Swift para apps Apple Watch con HealthKit
  • Desarrollo tvOS: Convertir JSON de recomendación de contenido a tipos Swift para apps de TV
  • Modelado MVVM SwiftUI: Vincular modelos API como propiedades @Published a ViewModels
  • Flujos reactivos Combine: Usar tipos de respuesta como salida de Publisher con JSONDecoder
  • Premodelado SwiftData/Core Data: Generar structs y añadir @Model/@NSManual para mapeo de entidades
  • Integración SDK terceros: Convertir ejemplos JSON de documentación SDK a tipos Swift
  • Preparación pruebas unitarias: Convertir mock JSON a tipos Swift para XCTest
  • Code review: Convertir JSON API a tipos Swift para discutir nomenclatura en revisiones
  • Desarrollo híbrido Flutter/React Native: Preparar modelos para módulos Swift nativos
  • Migración interfaces backend: Generar modelos cliente Swift desde documentación REST o Postman
  • Docencia: Demostrar mapeo JSON a tipos en cursos Swift/iOS
  • Apps salud y fitness: Convertir JSON de HealthKit/Fitbit a tipos Swift
  • Apps pago y finanzas: Convertir JSON de pasarelas de pago a modelos Swift
  • E-commerce: Convertir pedidos, productos, direcciones a structs Swift para SwiftUI
  • Apps noticias: Convertir respuestas CMS a tipos Swift para listas/detalle
  • Desarrollo servidor Vapor: Convertir JSON request/response a structs Swift para Codable
  • MapKit y datos geográficos: Convertir JSON de mapas a structs Swift para búsqueda y rutas

Cómo Usar

  1. Pega JSON en el editor izquierdo, o sube un archivo .json/.txt, o carga datos de ejemplo
  2. Tras 400ms de debounce, se genera automáticamente el código Swift struct/class en el panel derecho
  3. Si hay errores JSON, haz clic en "Reparar JSON" para corregir problemas comunes
  4. Verifica el resultado, añade protocolos como Codable/Equatable/Identifiable según necesites, copia o descarga el código

Características

  • Conversión pura en navegador: El análisis JSON y generación de código Swift se completan en el navegador mediante quicktype-core; ni el JSON original ni el código generado se suben a ningún servidor
  • Modo quicktype-core just-types: Genera declaraciones de propiedades struct/class Swift limpias sin imports, Codable/CodingKeys u otros comentarios, facilitando la personalización para tu proyecto
  • Conversión automática con debounce de 400ms: Tras pegar o modificar JSON, los tipos Swift se generan casi en tiempo real sin clics repetidos; el proceso es asíncrono y no bloquea la UI
  • Ejecución en Web Worker: quicktype-core se ejecuta en un Web Worker del navegador, evitando que el hilo principal se congele durante conversiones de JSON grandes
  • Inferencia de tipos inteligente: Mapea automáticamente String, Int, Double, Bool, [T] y tipos personalizados; arrays se infieren del primer elemento, sin tipado manual
  • Expansión automática de objetos anidados: Genera recursivamente tipos Swift independientes para cada objeto anidado, nombrados capitalizando la primera letra del campo
  • Inferencia automática de arrays: Los arrays JSON se convierten a [String]/[Int]/[Double]/[TipoPersonalizado]; arrays vacíos generan [Any] por defecto
  • Reparación de errores JSON con un clic: Corrige automáticamente errores comunes como comas finales, comillas simples, comillas faltantes y comentarios
  • Copia con un clic + descarga .swift: Copia el código Swift al portapapeles o descárgalo como archivo .swift para arrastrar a Xcode
  • Datos de ejemplo + subida de archivos: JSON de ejemplo estilo Swift integrado (con address/company/tags anidados), soporta drag-and-drop de archivos .json/.txt
  • Historial localStorage: Guarda automáticamente entradas recientes; reanuda edición tras refrescar o cerrar página accidentalmente
  • Editor responsivo de pantalla dividida: Vista previa en tiempo real, adaptativo para escritorio y móvil

Ejemplos de Código

Swift: URLSession + JSONDecoder parseando struct generado

swift

Uso más común en iOS/macOS: añade Codable a structs generados y decodifica con JSONDecoder.

import Foundation

struct User: Codable {
    let id: Int
    let name: String
    let email: String
    let isActive: Bool
    let tags: [String]
}

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)
}

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

Preguntas Frecuentes

¿Cómo convierto JSON a structs Swift?

Pega el JSON en el cuadro izquierdo. Tras 400ms de debounce, la herramienta llama a quicktype-core automáticamente y muestra el resultado en el panel derecho. También puedes subir archivos .json/.txt o cargar ejemplos integrados. Tras la conversión, copia con un clic o descarga como .swift.

¿El código Swift generado incluye Codable?

Por defecto no. Esta herramienta usa el modo just-types de quicktype-core, generando declaraciones de propiedades struct/class puras sin anotaciones Codable, Decodable o Encodable, ni sentencias import. Si necesitas Codable, añade : Codable tras generar (ej., struct User: Codable {}).

¿Qué estructuras JSON se admiten?

Todo JSON válido: tipos básicos (null, boolean, number, string), arrays unidimensionales o multidimensionales y objetos anidados de cualquier profundidad. La entrada raíz puede ser objeto o array; objetos primero, arrays inferidos del primer elemento.

¿Cómo se manejan los objetos JSON anidados?

La herramienta genera recursivamente tipos Swift independientes para cada objeto anidado. Si Root contiene un campo address, se genera un subtipo Address referenciado mediante var address: Address. Esto evita definiciones duplicadas y permite a Xcode rastrear correctamente las jerarquías.

¿Los campos array se convierten a arrays Swift?

Sí. Los arrays JSON se convierten a [T]. Elementos string → [String], enteros → [Int], flotantes → [Double], objetos → [TipoPersonalizado]. Arrays vacíos [] generan [Any]; se recomienda cambiar a tipos concretos tras generar.

¿Qué tipo se genera para campos null?

Los valores null no pueden tener tipo concreto inferido; se genera Any o tipo de respaldo. Se recomienda reemplazar null por valores de muestra o cambiar manualmente a Optional (ej., var phone: String?).

¿Puedo personalizar los nombres de struct generados?

Sí. Haz clic en el botón de nombre de tipo en la barra de herramientas para modificar el nombre raíz. Los subtipos se generan automáticamente capitalizando la primera letra de los campos (users → User, tags → Tag).

¿Qué pasa si el formato JSON es incorrecto?

La herramienta detecta errores JSON y muestra un botón "Reparar JSON" que corrige automáticamente: comas finales, comillas simples por dobles, claves sin comillas, comentarios, etc.

¿Se suben los datos a servidores?

Funciona completamente en el navegador local. Todo el procesamiento es mediante JavaScript (quicktype-core en Web Worker); los datos no se suben, registran ni cachean en la nube. JSON sensible puede usarse con seguridad.

¿El código generado se puede usar directamente en Xcode?

Sí. Es sintaxis Swift estándar que se puede copiar o descargar como .swift. Se recomienda añadir protocolos como Codable, Equatable, Identifiable según necesidades del proyecto.

¿Se admiten arrays JSON como entrada raíz?

Sí. Si la raíz es un array, se usa el primer elemento como plantilla para generar el tipo de elemento. [{"id":1,"name":"A"}] genera un struct Item referenciado como items: [Item].

¿Convertir JSON grande causa retardo?

No hay límite explícito, pero JSON muy grande ralentiza el navegador. Recomendaciones: convertir un módulo a la vez, dividir anidamiento profundo, usar quicktype CLI para JSON de varios MB.

¿JSON a Swift y JSON a TypeScript son intercambiables?

Ambos convierten JSON a tipos, pero con enfoques diferentes: Swift para apps nativas iOS/macOS, TypeScript para frontend. Proyectos full-stack deberían generar ambas versiones para consistencia.

¿Cómo añado Codable al código generado?

Añade : Codable tras la declaración struct/class (ej., struct User: Codable {}). Para Codable por defecto, puedes modificar el renderizador Swift de quicktype-core.

¿Se requiere internet? ¿Funciona en móviles?

Primera visita requiere internet para cargar recursos; después funciona offline desde caché. Navegadores móviles (iOS Safari, Android Chrome) funcionan con diseño responsivo.

¿Puedo modificar tipos individuales tras generar?

Sí. Cada tipo es un struct/class independiente. Puedes copiar tipos individuales o usar Rename en Xcode para refactorizar sin afectar otros tipos.

¿Se admite inferencia de enum Swift?

La inferencia de enums requiere sugerencias de tipo adicionales o entrada GraphQL/JSON Schema. Por defecto no se generan enums; puedes convertir manualmente structs a enum + Codable.

Solución de problemas

Mensaje "Por favor ingrese datos JSON" o panel derecho vacío

El cuadro de entrada está vacío. Pega JSON válido, carga un ejemplo o sube un archivo.

Mensaje "Unexpected token ... in JSON"

Formato JSON inválido: coma final, comillas simples en lugar de dobles, sintaxis JS object, o comentarios. Usa "Reparar JSON" para corregir automáticamente.

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.

Glosario

struct
Tipo por valor en Swift, adecuado para modelos de datos inmutables. Se copia al asignar. Esta herramienta genera struct por defecto.
class
Tipo por referencia en Swift para estado compartido o herencia. Se puede generar class bajo ciertas configuraciones.
Codable
Combinación de Decodable y Encodable en Swift. Permite a JSONDecoder parsear JSON. No se genera por defecto.
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.

Tabla de mapeo de tipos JSON a Swift

La herramienta infiere tipos Swift automáticamente según valores JSON:

Ejemplo JSONMétodo detecciónTipo SwiftNotas
nullvalue === nullAny? u OptionalNo se puede inferir tipo; cambiar a Optional<T>
true/falsetypeof value === 'boolean'BoolMapeo directo a Bool
42typeof value === 'number' && Number.isInteger(value)IntEnteros mapean a Int
"hello"typeof value === 'string'StringCadenas mapean a String
"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

Todas las operaciones de esta herramienta se completan localmente en tu navegador mediante JavaScript (quicktype-core/Web Worker). Los datos JSON y código Swift generado nunca se suben a servidores ni se almacenan en la nube. JSON sensible puede usarse con seguridad; cerrar la página borra todo.

Authoritative References