swift - Swift 4 + Alamofire:解析自定义结构数组
问题描述
我的 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)
}
}
推荐阅读
- python - 使用 Dash Cytoscape 在回调中更改节点的标签
- tensor - AttributeError:类型对象“h5py.h5.H5PYConfig”没有属性“__reduce_cython__”,版本不兼容?
- java - Kafka Streams API-过滤器运算符:“错误:类型参数的数量错误;需要 1”
- c# - 分配谓词变量而不是 lambda 表达式
- django - 具有标记为 pk + fk 的字段的表上的 Django HyperlinkedModelSerializer
- python - scipy dendrogram 不一致地杀死 Spyder 内核
- python - 在 Python 中查找得分最高的单词
- flutter - 如何在 shared_preferences 中创建一个 bool 列表并在那里存储值
- pine-script - 我的策略不执行交易,如何解决?
- angular - 在 Angular 10 上从 node-sass 切换到 sass(dart-sass) 时出错