来自Alamofire响应的SWift 4 JSONDecoder解码

时间:2018-04-01 10:42:59

标签: swift alamofire swift4 jsondecoder

我有一个包含其他结构和数组的结构。

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)

1 个答案:

答案 0 :(得分:2)

错误很明显:

response.result.value显然是一个字典(__NSDictionaryI),无法转换为(NS)Data。这意味着JSON已经反序列化。

为了能够使用JSONDecoder,您必须更改Alamofire设置以返回原始Data