我有一个包含其他结构和数组的结构。
public struct Report: Codable {
let s:Student;
let vio:[VIO];
let stuPresence: [StuPresence];
}
我正在尝试新的JSONDecoder()
将alamofire响应转换为我的结构。
sessionManager.request( self.url_report+"?d="+date, method: .get, parameters: nil).responseJSON{ response in
if response.response?.statusCode == 200 {
debugPrint(response)
do{
let r = try JSONDecoder().decode(Report.self, from: response.result.value as! Data)
debugPrint(r);
}catch{
self.showMessage(message: self.general_err)
}
}
}
问题是,在我的Report
结构中解码后,我得到数字(从调试模式检查),而不是字符串。我究竟做错了什么?
更新:它也会出错
Could not cast value of type '__NSDictionaryI' (0x108011508) to 'NSData' (0x108010090)
答案 0 :(得分:2)
错误很明显:
response.result.value
显然是一个字典(__NSDictionaryI
),无法转换为(NS)Data
。这意味着JSON已经反序列化。
为了能够使用JSONDecoder
,您必须更改Alamofire
设置以返回原始Data