如何使用 swift Codable 协议解码以“[”开头的 JSON
How to decode JSON starting with "[" using swift Codable Protocol
我遇到了来自服务器的 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
如果没有命名,有没有办法使用编码键来处理数组?
如果没有,如何处理这种情况?
json的根是一个要解码的数组应该是[Person].self
你可以试试
struct Person: Codable {
let name: String
let age: Int
}
let res = try? JSONDecoder().deocde([Person].self,from:data)
print(res)
我遇到了来自服务器的 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
如果没有命名,有没有办法使用编码键来处理数组?
如果没有,如何处理这种情况?
json的根是一个要解码的数组应该是[Person].self
你可以试试
struct Person: Codable {
let name: String
let age: Int
}
let res = try? JSONDecoder().deocde([Person].self,from:data)
print(res)