我有一个JSON有效负载,其格式如下:
{
items: [
{
id: 1,
anotherKey: anotherValue
},
{
id: 2,
anotherKey: anotherValue
}
]
}
这是我用来解码有效负载的代码:
struct Suggestions : Codable {
let items: [EmployeeDTO]
}
if let json = try? JSONDecoder().decode(Suggestions.self, from: response.data!) {
print("decoding success, json is \(json)")
}
else {
print("failed")
}
我的EmployeeDTO也在外部文件中定义为Codeable结构。我遇到的问题是解码只有在我的数组只有1个结果时才有效。换句话说,只有一个EmployeeDTO对象的数组。只要我有一个包含2个或更多对象的数组,解码就会失败并直接进入其他对象。关于为什么会这样的想法?我很难过。这是我一直用作解析带有数组的嵌套对象的指南的文档:http://benscheirman.com/2017/06/ultimate-guide-to-json-parsing-with-swift-4/