Back to code Swift

Convertir el JSON de una API en objetos con fechas reales

Codable con claves renombradas y fechas ISO 8601: el JSON entra como texto y sale como estructuras tipadas.

This post is not in your language yet; you are seeing it in Spanish. The code is the same.

The problem

La API devuelve creado_en como texto y en snake_case. La app necesita un Date de verdad y nombres al estilo Swift, sin convertir campo por campo a mano.

Swift
import Foundation

struct Pedido: Codable {
    let id: Int
    let cliente: String
    let total: Double
    let creadoEn: Date

    enum CodingKeys: String, CodingKey {
        case id, cliente, total
        case creadoEn = "creado_en"
    }
}

let json = """
[{"id": 1, "cliente": "Ana", "total": 149.9, "creado_en": "2026-03-01T10:30:00Z"}]
""".data(using: .utf8)!

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601

do {
    let pedidos = try decoder.decode([Pedido].self, from: json)
    for p in pedidos { print("#\(p.id) \(p.cliente): \(p.total) el \(p.creadoEn)") }
} catch {
    print("JSON inválido:", error)
}

Why it is written this way

  1. Al declarar Codable, el compilador escribe solo la conversión entre JSON y la estructura.
  2. CodingKeys traduce nombres: creado_en en el JSON, creadoEn en el código.
  3. dateDecodingStrategy = .iso8601 convierte el texto de la fecha en un Date sin código extra.
  4. Si falta un campo o el tipo no coincide, decode lanza un error que dice exactamente cuál.
How to try it

Guardalo como pedidos.swift y corré: swift pedidos.swift. Borrá un campo del JSON para ver el error que da.

Watch out

.iso8601 no acepta fracciones de segundo ("10:30:00.123Z"). Si tu API las manda, hace falta un ISO8601DateFormatter con esa opción o un formato propio.

Adapt it to your case with AI

The button copies this prompt with the code pasted below it. Replace the brackets with your own details and paste it into ChatGPT, Claude, Gemini or Copilot.

The prompt
Tengo este modelo Codable en Swift. Mi API devuelve este JSON: [EJEMPLO DE JSON REAL]. Generá las estructuras completas, con los campos opcionales marcados como tales, las fechas en el formato que usa mi API ([FORMATO DE FECHA]) y un ejemplo de llamada con URLSession y async/await que maneje error de red, código HTTP distinto de 200 y JSON inválido por separado.

Example written and reviewed by hand.

Share

Comments

No comments yet. Yours can be the first.

Plain text only, no links. No email is requested. Comments are reviewed before they are published.

Did you adapt it to something of yours?

Tell me what you solved with it, or what it was missing.

Keep trying

More code

See all
Darinel Ortega Online · I reply during the day
Today
Hello. I'm not selling anything here: this is for exchanging knowledge about technology.
Write whatever you like — you can send text, images or documents. Messages reach my console and I reply from there.

An open conversation to share knowledge. Messages reach my console and I reply from there.

Let us book a conversation

Pick the day and time that work for you. Thirty minutes, no sales pitch.

Video call

For a video call, just ask for one here and I'll send you the session link.