簡體   English   中英

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

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

由於使用 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.. } 

我得到錯誤

在 scope 中找不到“ResponseType”

有沒有人有什么建議?

與返回字典或數組的.responseJSON不同, .responseDecodable將 JSON 反序列化為結構或類。

您必須創建一個符合Decodable的適當模型,在您的代碼中它由ResponseType(.self)表示。

success案例的關聯值是模型的根結構。

棄用(黃色警告)意味着 API 仍然可以運行。

旁注:JSON 字典永遠不是[String: Any?]該值始終是非可選的。

在 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