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\")."
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:
Receipt
has more key-value pairs, then you would have to manually decode those as well.let data = """
[{
"expires_date": "2019"
},
{
}]
""".data(using: .utf8)!
do {
let obj = try JSONDecoder().decode([Receipt].self, from: data)
print(obj)
}
catch {
print(error)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With