【问题标题】:Different key type for the same json object in network response网络响应中相同 json 对象的不同键类型
【发布时间】:2019-09-27 05:07:54
【问题描述】:

我的客户有一个返回 Article 对象的服务。有一个 id 属性,它是 UInt64 类型。在同一个 api 中,当您询问类别文章时,您会收到文章的响应,但 id 是一个字符串。目前没有办法有人会改变这个愚蠢的事情,所以我必须找到一种解决方法来解析这两个答案。我的模型是这样的:

struct Article {
  let id: UInt64
  let categoryName: String?
}

extension Article: Decodable {
  private enum Keys: String, CodingKey {
    case id
    case categoryName
}

init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: Keys.self)

    id = try container.decode(UInt64.self, forKey: Keys.id)
    categoryName = try container.decodeIfPresent(String.self, forKey: Keys.categoryName)
}

如何查看Keys.id的类型并使用正确的方法进行解码? 我必须同时使用两个

   id = try container.decode(UInt64.self, forKey: Keys.id)
   id = try container.decode(String.self, forKey: Keys.id) 

在这两种情况下都正确解析我的对象。提前致谢

【问题讨论】:

    标签: json swift decodable


    【解决方案1】:

    如果您想要解决方法,那么下面的答案就是这样做的。我不知道这是否也是一种可能的好方法。期待改进这个答案。欢迎提出建议。

    extension Article: Decodable {
    private enum Keys: String, CodingKey {
        case id
        case categoryName
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: Keys.self)
        // check if id is of type UInt64
        do{
            id = try container.decodeIfPresent(UInt64.self, forKey: Keys.id) ?? 0
    
        }catch{
            // if id is of String type convert it to UInt64
            // do catch can be used here too
            let str = try container.decodeIfPresent(String.self, forKey: Keys.id)
            id = UInt64(str ?? "0") ?? 0
    
        }
        categoryName = try container.decode(String.self, forKey: Keys.categoryName)
    
    }
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      • 2015-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多