Swift Codable null handling

后端 未结 2 1084
一生所求
一生所求 2021-02-05 14:46

I have a struct that parse JSON using Codable.

struct Student: Codable {
    let name: String?
    let amount: Double?
    let adress: String?
}
         


        
2条回答
  •  天命终不由人
    2021-02-05 15:15

    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

提交回复
热议问题