2

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

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

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

谢谢

4

1 回答 1

9

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

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关键

于 2018-07-03T18:26:35.253 回答