【问题标题】:How to use responseDecodable instead of responseJSON using Alamofire 6如何使用 Alamofire 6 使用 responseDecodable 而不是 responseJSON
【发布时间】:2022-08-02 11:49:52
【问题描述】:

由于使用 Alamofire 时 JSON 序列化失败,我的一个应用程序不再工作。

\'responseJSON(queue:dataPreprocessor:emptyResponseCodes:emptyRequestMethods:options:completionHandler:)\' 已弃用:responseJSON 已弃用并将在 Alamofire 6. 改用 responseDecodable。

对于具有以下几行的代码

AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: [:]).responseJSON { response in.. } 

当更改为

AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: [:])
 .responseDecodable { response in... }

然后我得到错误

无法推断通用参数 \'T\'

所以我添加以下内容

AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: [:])
  .responseDecodable(of: ResponseType.self) { response in.. } 

我得到错误

在范围内找不到 \'ResponseType\'

有没有人有什么建议?

  • 它已被弃用,所以它应该仍然有效。如果你有一个 Codable 结构,responseDecodable 就可以工作,这似乎不是你的情况。要么使用Codable,要么使用 JSONSerialization 对自己进行序列化。见stackoverflow.com/questions/70789753/…
  • 您需要将 ResponseType 替换为要将 JSON 解码为的实际 Decodable 类型。

标签: ios swift alamofire


【解决方案1】:

与返回字典或数组的.responseJSON 不同,.responseDecodable 将 JSON 反序列化为结构或类。

您必须创建一个符合Decodable 的适当模型,在您的代码中它由ResponseType(.self) 表示。

success case 的关联值是模型的根结构。

已弃用(黄色警告)表示 API 仍在运行。

旁注:JSON 字典是绝不[String: Any?] 该值始终是非可选的。

【讨论】:

    【解决方案2】:

    结构可解码类型:可解码 { 让网址:字符串 让名称:字符串 }

    AF.request(urlString).responseDecodable(of: [DecodableType].self) { 响应 切换响应。结果 { 案例 .success(让 dTypes): print(dTypes.map { "($0.name) ($0.name)" }) 案例.失败(让错误): 打印(错误) } }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-19
      • 1970-01-01
      • 2020-08-12
      • 2019-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多