Was browsing through Codable and got this issue.
So to be very clear here it is,
If the JSON/response would contain null
as the value, its interpreted as nil
. And hence for that reason one of the model's property which might contain null
should be marked as optional.
For Example, consider the below JSON response,
{
"name": "Steve",
"amount": null,
"address": "India"
}
The model should be as below, cos amount
is returning null
.
struct Student: Codable {
let name: String
let amount: Double?
let address: String
}
Suggestion
: In case, if you would write a init(from decoder: Decoder) throws
, always use something like below, for optional properties.
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
amount = try values.decodeIfPresent(String.self, forKey: .amount)
//so on...
}
Even if you add do-catch
block with try? decoder....
it can be captured if fails. Hope thats clear!! Its simple but very difficult to find the issue even if the model is containing 5 or more properties with some containing null
values