可解码的JSONDecoder处理相同值的不同编码键

Mis*_*ssa 2 json swift decodable jsondecoder

我正在使用Swift可解码协议来解析我的JSON响应:

{  
    "ScanCode":"4122001131",
    "Name":"PINK",
    "attributes":{  
            "type":"Product",          
            "url":""
     },
    "ScanId":"0000000kfbdMA"
}
Run Code Online (Sandbox Code Playgroud)

我遇到一个问题,有时我会用键“ Id”而不是“ ScanId”来获取ScanId值。有办法解决这个问题吗?

谢谢

vad*_*ian 7

您必须编写一个自定义的初始化程序来处理这些情况,例如

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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

首先尝试解码一个密钥,如果它无法解码另一个密钥。

为了方便起见,我跳过了attributes