【问题标题】:Codable Handle Single or Array [duplicate]可编码句柄单个或数组 [重复]
【发布时间】:2019-11-26 16:13:47
【问题描述】:

当数组包含一个元素时,我们的 API 在数据中发送单个对象:

{
  "data":{
    "name":"ABC",
    "age":"26"
  }
}

但是当数组中有更多元素时,响应就在数组中

{
  "data":[{
    "name": "ABC",
    "age" : "26"
  },
  {
    "name": "XYZ",
    "age" : "22"
  }]
}

【问题讨论】:

  • 使用 Json 解码器解码响应时,您必须指定一个类型。以上两种情况单次解码是不行的,如果API在第一种情况下也返回一个数组就很容易了。
  • @Shubham 遗憾的是 API 无法更改,因此必须找到处理这种情况的方法。
  • 我明白了,如果无法修复 API,您可以使用@Sh_khan 的答案来解码数据。

标签: ios swift codable


【解决方案1】:

对我来说似乎是一个糟糕的 API 设计。

无论计数如何,您的 API 都应该在您的 data 字段中返回一个数组。

{ "data":[{ "name": "XYZ", "age" : "22" }] }

{ "data":[{ "name": "ABC", "age" : "26" }, { "name": "XYZ", "age" : "22" }] }

【讨论】:

    【解决方案2】:

    这样做

    struct Root  : Codable {
    
       let data:[DItem]
    
       init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        do {
             data = try container.decode([DItem].self, forKey: .data)
        }
        catch {
             let res = try container.decode(DItem.self, forKey: .data)
            data = [res]
        }
    
     }
    }
    
    struct DItem: Codable {
       let name,age:String 
    }
    

    let res = try JSONDecoder().decode(Root.self, from:data)
    

    直到你修复响应

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多