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)
}
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")