I'm getting an exception when decoding this json to the Device
struct below.
JSON
{
"SerialNumber": "123",
"Model": "iPhone14"
"Brand": "Apple"
}
Swift struct:
struct Device : Codable, Identifiable {
var id = UUID().uuidString
let SerialNumber : String
let Model : String
let Brand : String
}
To get around this, I have to add the following to my struct since id
is not part of the json. I need to define the fields that I want to be decoded.
private enum CodingKeys: String, CodingKey {
case SerialNumber, Model, Brand
}
But I don't want to do that.That means that every time the web service developer decides to remove a field from the json, I will have to change my code. I haven't tested the other way around where the json has some extra fields that's not in the struct.
Is there a way in swift to just decode the fields that are present in both the json and the struct?
The general approach is that you add the CodingKeys
enum when your struct has one or more properties that will never be in the JSON. The CodingKeys
will list just the properties that may be in the JSON.
For struct properties that might not always be in the JSON, you make those properties optional.
For struct properties that will always be in the JSON, you make those properties non-optional.
So in your case you need to add CodingKeys
for the three non-id properties and you want to make the other three properties optional if you need to handle any of them not being in the JSON.
struct Device : Codable, Identifiable {
var id = UUID().uuidString
let SerialNumber : String?
let Model : String?
let Brand : String?
private enum CodingKeys: String, CodingKey {
case SerialNumber, Model, Brand
}
}