2

I'm using Swift decodable protocol to parse my JSON response:

{  
    "ScanCode":"4122001131",
    "Name":"PINK",
    "attributes":{  
            "type":"Product",          
            "url":""
     },
    "ScanId":"0000000kfbdMA"
}

I'm running into an issue where sometimes I get the ScanId value with a key "Id" instead of "ScanId". Is there a way to work around that?

Thanks

1 Answer 1

10

You have to write a custom initializer to handle the cases, for example

struct Thing : Decodable {
    let scanCode, name, scanId : String

    private enum CodingKeys: String, CodingKey { case scanCode = "ScanCode", name = "Name", ScanID, Id }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        scanCode = try container.decode(String.self, forKey: .scanCode)
        name = try container.decode(String.self, forKey: .name)
        if let id = try container.decodeIfPresent(String.self, forKey: .Id) {
            scanId = id
        } else {
            scanId = try container.decode(String.self, forKey: .ScanID)
        }
    }
}

First try to decode one key, if it fails decode the other.

For convenience I skipped the attributes key

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.