7

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?

RileyDev
  • 2,950
  • 3
  • 26
  • 61
  • It's deprecated, so it should still work. `responseDecodable` works if you have a `Codable` struct, which doesn't seem to be your case. Either use `Codable`, or serialize yourself using JSONSerialization. See https://stackoverflow.com/questions/70789753/update-responsejson-to-responsedecodable-in-swift/70804441#70804441 – Larme May 11 '22 at 13:55
  • You need to replace `ResponseType` with the actual `Decodable` type you want to decode the JSON into. – Jon Shier May 11 '22 at 17:52

2 Answers2

5

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.

vadian
  • 274,689
  • 30
  • 353
  • 361
1

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)
    }
}
Monica Granbois
  • 6,632
  • 1
  • 17
  • 17
Scott
  • 11
  • 2