首页 文章

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

提问于
浏览
0

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

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

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

谢谢

1 回答

  • 1

    例如,您必须编写自定义初始值设定项来处理案例

    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

相关问题