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

Decodable JSONDecoder handle different coding keys for the same value

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

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

我 运行 遇到一个问题,有时我使用键 "Id" 而不是 "ScanId" 获取 ScanId 值。 有办法解决这个问题吗?

谢谢

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

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)
        }
    }
}

首先尝试解码一个密钥,如果失败则解码另一个。

为方便起见,我跳过了 attributes