I am trying to parse a response using the JSONDecoder
. If there is value for the corresponding key then it goes well, but if there is null value for a key then it fails to compile with the following error.
valueNotFound(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "Results", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "VehicleName", intValue: nil)], debugDescription: "Expected String value but found null instead.", underlyingError: nil))
guard let obj = try? JSONDecoder().decode(ShipmentsResponse.self, from: json) else {return}
here is the Shipment class that i defied
class ShipmentResponse : Codable {
var ItemId: String = ""
var VehicleName: String = ""
var VehicleNumber: String = ""
convenience required init(from decoder: Decoder) throws
{
self.init()
let values = try decoder.container(keyedBy: CodingKeys.self)
ItemId = try values.decode(String.self, forKey: .ItemId)
do {
_ = try values.decode(String.self, forKey: .VehicleName)
} catch {
print(error)
}
VehicleName = try values.decode(String.self, forKey: .VehicleName)
VehicleNumber = try values.decode(String.self, forKey: .VehicleNumber)
}
}
Here is the json
{
"ItemId": "8af66c87-9099-42a7-8a34-39def02160ac",
"VehicleName": null,
"VehicleNumber": null
}