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
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 byResponseType(.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.In Alamofire -> Documentation/Usage.md, I found the definition of the Decodable, so I try like this, then found working.