【问题标题】:SWift 4 JSONDecoder decode from Alamofire response来自 Alamofire 响应的 SWIFT 4 JSONDecoder 解码
【发布时间】:2018-09-10 20:09:59
【问题描述】:

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

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)

【问题讨论】:

  • response.data 而不是 response.result.value
  • 在这些更改之后,我最终进入了catch
  • 问题可能出在模型上,你能在问题中给出一个儿子样本和模型结构吗?

标签: swift alamofire swift4 jsondecoder


【解决方案1】:

错误很明显:

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

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

【讨论】:

  • 对如何返回原始数据有什么建议吗?我尝试了很多变化,但总是以 catch 块结束。
  • 按照 cmets (response.data) 中的建议,您会遇到什么错误?你甚至不处理实际的错误。
  • 如果您最终进入catch 块,则有一个errorprint它。 self.general_err 毫无意义。永远不要忽略在 catch 块中传递的 errors。
  • Error info: valueNotFound(Swift.Int, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "s", intValue: nil), CodingKeys(stringValue: "id", intValue: nil)], debugDescription: "Expected Int value but found null instead.", underlyingError: nil))
  • 使用 CodingKeys 并留下密钥。为属性分配默认值或使其可选。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-17
  • 2014-11-24
  • 1970-01-01
  • 2016-01-18
  • 2019-03-05
  • 2019-04-15
相关资源
最近更新 更多