我在解析来自服务器的数据时遇到问题。我有一个JSON,它有一个对象数组,如下所示:
{
"items": [
{
"itemType": {
"id": 12,
"tagId": "FCHA78558D"
},
"parts": [
{
"partId": 52,
"manufacturer": "xxx"
},
{
"partId": 53,
"manufacturer": "xxx"
},
{
"partId": 54,
"manufacturer": "xxx"
}
],
"description": "yyy"
},
{
"itemType": {
"id": 13,
"tagId": "FCHA755158D"
},
"parts": [
{
"partId": 64,
"manufacturer": "xxx"
},
{
"partId": 65,
"manufacturer": "xxx"
}
],
"description": "zzz"
}
]
}
我只想获得这一个对象数组,所以我实现了这样的类:
class User : Object, Decodable {
var items = List<Equipment>()
}
在Alamofire中,我下载JSON,将其解析为数据,然后在do catch块中,我收到一个错误:
let items = try JSONDecoder().decode(User.self, from: receivedValue)
错误:
â¿ DecodingError
â¿ typeMismatch : 2 elements
- .0 : Swift.Array<Any>
â¿ .1 : Context
â¿ codingPath : 2 elements
- 0 : CodingKeys(stringValue: "items", intValue: nil)
â¿ 1 : _JSONKey(stringValue: "Index 0", intValue: 0)
- stringValue : "Index 0"
â¿ intValue : Optional<Int>
- some : 0
- debugDescription : "Expected to decode Array<Any> but found a dictionary instead."
- underlyingError : nil
这很奇怪,因为它确实是一个对象数组。我尝试将items属性设置为String以查看结果,然后得到:
- debugDescription : "Expected to decode String but found an array instead."
我有过几次这样的错误,但我总能找到解决办法。