Search code examples
jsonswiftdecodablejsondecoder

Decodable JSONDecoder handle different coding keys for the same value


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


Solution

  • 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