0Pricing
SwiftUI Academy · Lección

Decodificar JSON con Codable

Convierta JSON en structs de modelo de Swift.

Decodificar JSON con Codable es una lección gratuita de SwiftUI Academy en CoddyKit. Esta es la lección 1 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de SwiftUI Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de SwiftUI Academy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Why JSON Needs Decoding

APIs speak JSON, a text format Swift cannot use directly. You decode that text into real Swift types you can work with. 📦

Meet Codable

The Codable protocol lets a type convert itself to and from JSON automatically, so you rarely write parsing code by hand.

A Codable Struct

Just add Codable to your struct. Swift generates the encoding and decoding for every stored property for you.

struct User: Codable {
    let id: Int
    let name: String
}

Matching JSON Keys

Swift maps each property name straight to the matching JSON key. So "name" in JSON fills the name property exactly.

{ "id": 1, "name": "Ada" }

Decoding with JSONDecoder

A JSONDecoder turns raw Data into your type. You tell it which type to expect, and it does the rest.

let user = try JSONDecoder()
    .decode(User.self, from: data)

Working With Data

Network responses arrive as Data, a bag of bytes. The decoder reads those bytes and produces your typed value.

Decoding Arrays

To decode a JSON list, ask for an array of your type. One call gives you a ready-to-use Swift array. 🎉

let users = try JSONDecoder()
    .decode([User].self, from: data)

Renaming with CodingKeys

When JSON keys differ from your names, add CodingKeys to map a snake_case key onto a clean Swift property.

enum CodingKeys: String, CodingKey {
    case name = "full_name"
}

Optional Properties

Mark a property optional when the key may be missing. The decoder simply sets it to nil instead of throwing.

let avatar: String?

Decoding Can Throw

If the JSON shape does not match your type, decoding throws. Always wrap the call in try so you can handle bad data.

Nested Models

Nested JSON objects become nested structs. Make each level Codable and Swift decodes the whole tree at once.

struct Post: Codable {
    let author: User
}

Quick Check

Quick check on turning JSON into Swift types.

Recap: Codable

You learned that Codable plus JSONDecoder maps JSON into typed Swift values, with CodingKeys for renames and optionals for missing keys. 🙌

Preguntas frecuentes

¿La lección «Decodificar JSON con Codable» es gratis?

Sí — el texto completo de «Decodificar JSON con Codable» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de SwiftUI Academy, actualiza a CoddyKit PRO. El curso de SwiftUI Academy incluye 4 lecciones en total.

¿Qué aprenderé en «Decodificar JSON con Codable»?

Convierta JSON en structs de modelo de Swift. Practicas SwiftUI Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar SwiftUI Academy?

No se requiere experiencia previa. SwiftUI Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 4.

¿Cuánto tiempo toma la lección «Decodificar JSON con Codable»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de SwiftUI Academy?

Sí. Cada lección de SwiftUI Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Decodificar JSON con Codable
  2. Llamar a APIs con URLSession
  3. El modificador .task
  4. Estados de carga y error
← Volver a SwiftUI Academy