我的 API 返回以下 JSON([CustomClass] 数组):
[{
"name": "Name A",
"startingDate": "2018-01-01",
"duration": 4
},
{
"name": "Name B",
"startingDate": "2018-01-01",
"duration": 4
}
]
我正在使用 Alamofire 发出请求,然后解析 JSON:
static func test(parametersGet:Parameters, completion: @escaping ([CustomStruct]?, Error?) -> Void ) {
Alamofire.request(API.test, parameters: parametersGet).validate().responseJSON { response in
switch response.result {
case .success:
if let json = response.result.value {
let workoutCards = json as! [CustomStruct]
completion(workoutCards, nil)
}
case .failure(let error):
completion(nil, error)
}
}
}
CustomStruct 它只是一个带有这些键的 Codable 结构。
我收到以下错误:“无法将‘__NSDictionaryI’类型的值转换为‘Project.CustomStruct’”。如何解析 JSON?
最佳答案
在您的情况下,您需要使用 JSONDecoder 将 jsonData 解码为 [CustomStruct]
Alamofire.request(API.test, parameters: parametersGet).validate().responseJSON { response in
switch response.result {
case .success:
if let jsonData = response.data {
let jsonDecoder = JSONDecoder()
do {
let workoutCards = try jsonDecoder.decode([CustomStruct].self, from: jsonData)
completion(workoutCards, nil)
}catch let error{
print(error.localizedDescription)
completion(nil, error)
}
}
case .failure(let error):
completion(nil, error)
}
}
关于 swift 4 + Alamofire : parse array of custom struct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50913632/