Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I decode a JSON to a Swift struct ignoring all the fields that are not in both the json and the struct?

I’m getting an exception when decoding this json to the Device struct below.

JSON

    {
        "SerialNumber": "123",
        "Model": "iPhone14"
        "Brand": "Apple"
    }

Swift struct:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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?

>Solution :

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
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading