Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

200
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda