Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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\")."

like image 252
mandem112 Avatar asked Oct 19 '25 08:10

mandem112


1 Answers

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)
}
like image 110
staticVoidMan Avatar answered Oct 20 '25 23:10

staticVoidMan