Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

198
Vistas
How to ignore nil json values in codable

I currently getting receipts back both Auto-Renewable and Non-Renewable. But the Non-Renewable doesn't come back with expires_date json key. How can I ignore this. I'm trying to avoid making expires_date an optional. When I make it optional Apple sends a response back. Is there way I can decode the json without making expires_date optional.

struct Receipt: Codable {

    let expiresDate: String

    private enum CodingKeys: String, CodingKey {
        case expiresDate = "expires_date"
    }
}

Right now I can currently get

"No value associated with key CodingKeys(stringValue: \"expires_date\", intValue: nil) (\"expires_date\")."

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

You will have to implement your own init(from: Decoder) and use decodeIfPresent(_:forKey:) before nil coalescing to a default value.

struct Receipt: Codable {
    let expiresDate: String
    
    enum CodingKeys: String, CodingKey {
        case expiresDate = "expires_date"
    }
    
    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)        
        self.expiresDate = try values.decodeIfPresent(String.self, forKey: .expiresDate)
            ?? "1970" //Default value
    }        
}

NOTE:

  • If Receipt has more key-value pairs, then you would have to manually decode those as well.

Usage Example:

let data = """
[{
  "expires_date": "2019"
},
{

}]
""".data(using: .utf8)!

do {
    let obj = try JSONDecoder().decode([Receipt].self, from: data)
    print(obj)
}
catch {
    print(error)
}
over 4 years ago · Santiago Trujillo Denunciar

0

How about manual decode it:

struct Receipt: Codable {

    let expiresDate: String

    private enum CodingKeys: String, CodingKey {
        case expiresDate = "expires_date"
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        if let expDate = try? values.decode(String.self, forKey: .expiresDate) {
            self.expiresDate = expDate
        } else {
            self.expiresDate = "sth"
        }
    }
}

Example:

struct Receipt: Codable {

    let expiresDate: String
    let b: String

    private enum CodingKeys: String, CodingKey {
        case expiresDate = "expires_date"
        case b = "b"
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        if let expDate = try? values.decode(String.self, forKey: .expiresDate) {
            self.expiresDate = expDate
        } else {
            self.expiresDate = "sth"
        }
        b = try values.decode(String.self, forKey: .b)
    }
}


let a = """
{
    "b": "asdf"
}
""".data(using: .utf8)!
let myStruct = try JSONDecoder().decode(Receipt.self, from: a)
print(myStruct) //Receipt(expiresDate: "sth", b: "asdf")
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda