skip to Main Content

One of my apps no longer works due to JSON serialisation failing when using Alamofire.

‘responseJSON(queue:dataPreprocessor:emptyResponseCodes:emptyRequestMethods:options:completionHandler:)’
is deprecated: responseJSON deprecated and will be removed in
Alamofire 6. Use responseDecodable instead.

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

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

Does anyone have any suggestions?

2

Answers


  1. Unlike .responseJSON which returns a dictionary or array .responseDecodable deserializes the JSON into structs or classes.

    You have to create an appropriate model which conforms to Decodable, in your code it’s represented by ResponseType(.self).

    The associated value of the success case is the root struct of the model.

    But deprecated (in a yellow warning) means the API is still operational.

    Side note: A JSON dictionary is never [String: Any?] the value is always non-optional.

    Login or Signup to reply.
  2. In Alamofire -> Documentation/Usage.md, I found the definition of the Decodable, so I try like this, then found working.

    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)
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search