简体   繁体   English

如何使用 Alamofire 6 使用 responseDecodable 而不是 responseJSON

[英]How to use responseDecodable instead of responseJSON using Alamofire 6

One of my apps no longer works due to JSON serialisation failing when using Alamofire.由于使用 Alamofire 时 JSON 序列化失败,我的一个应用程序不再工作。

'responseJSON(queue:dataPreprocessor:emptyResponseCodes:emptyRequestMethods:options:completionHandler:)' is deprecated: responseJSON deprecated and will be removed in Alamofire 6. Use responseDecodable instead. 'responseJSON(queue:dataPreprocessor:emptyResponseCodes:emptyRequestMethods:options:completionHandler:)' 已弃用:responseJSON 已弃用并将在 Alamofire 6 中删除。请改用 responseDecodable。

For code with the following lines对于具有以下几行的代码

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

When changing to当更改为

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

Then I get the error然后我得到错误

Generic parameter 'T' could not be inferred无法推断通用参数“T”

So I add the following所以我添加以下内容

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

I get the error我得到错误

Cannot find 'ResponseType' in scope在 scope 中找不到“ResponseType”

Does anyone have any suggestions?有没有人有什么建议?

Unlike .responseJSON which returns a dictionary or array .responseDecodable deserializes the JSON into structs or classes.与返回字典或数组的.responseJSON不同, .responseDecodable将 JSON 反序列化为结构或类。

You have to create an appropriate model which conforms to Decodable , in your code it's represented by ResponseType(.self) .您必须创建一个符合Decodable的适当模型,在您的代码中它由ResponseType(.self)表示。

The associated value of the success case is the root struct of the model. success案例的关联值是模型的根结构。

But deprecated (in a yellow warning) means the API is still operational.弃用(黄色警告)意味着 API 仍然可以运行。

Side note: A JSON dictionary is never [String: Any?] the value is always non-optional.旁注:JSON 字典永远不是[String: Any?]该值始终是非可选的。

In Alamofire -> Documentation/Usage.md, I found the definition of the Decodable, so I try like this, then found working.在 Alamofire -> Documentation/Usage.md 中,我找到了可解码的定义,所以我尝试这样,然后发现工作。

struct DecodableType: Decodable { 
    let url: String 
}

AF.request(urlString).responseDecodable(of: DecodableType.self) { response in
    switch response.result {
        case .success(let dTypes):
            print(dTypes.url})
        case .failure(let error):
            print(error)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM