如何使用快速可编码协议以“ [”开头的JSON解码

时间:2019-09-27 22:03:38

标签: json swift codable

我遇到了来自服务器的JSON响应,需要处理它。

基本上,JSON的根级别是数组而不是字典。例如:

[
  {
    "name": "Joe",
    "age": 50
  },
]

我已经建立了一个符合Codable的结构:

struct response: Codable {
    let responseArray: [Person]
}

struct person: Codable {
    let name: String
    let age: Int

    enum CodingKeys: String, CodingKey {
        case name = "name"
        case age = "age"
    }
}

尝试解码时出现以下错误:

▿ DecodingError
  ▿ typeMismatch : 2 elements
    - .0 : Swift.Dictionary<Swift.String, Any>
    ▿ .1 : Context
      - codingPath : 0 elements
      - debugDescription : "Expected to decode Dictionary<String, Any> but found an array instead."
      - underlyingError : nil

如果没有命名,是否可以使用编码键处理数组?

如果没有,那么如何处理这种情况?

1 个答案:

答案 0 :(得分:1)

json的根是数组,请执行[Person].self您可以尝试

struct Person: Codable {
    let name: String
    let age: Int  
}
let res = try? JSONDecoder().deocde([Person].self,from:data)
print(res)