代码之家  ›  专栏  ›  技术社区  ›  Missa

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

  •  2
  • Missa  · 技术社区  · 7 年前

    我正在使用swift可解码协议解析我的json响应:

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

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

    谢谢

    1 回复  |  直到 7 年前
        1
  •  6
  •   vadian    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)
            }
        }
    }
    

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

    为了方便我跳过了 attributes 钥匙