Joel Podrebarac
Joel Podrebarac

Reputation: 46

Alamofire 5.5 responseDecodable on JSON array

I am trying to decode an api response that just responds with an array. All the examples I see for using responseDecodable are a dictionary with a data key or something. But when I just pass [Movie].self into as the decoder I get:

failure(Alamofire.AFError.responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.decodingFailed(error: Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "name", intValue: nil), Swift.DecodingError.Context(codingPath: responseDecodable

I'm assuming I'm not doing this right, looking for some help

GET /request

Response:

[{"id": 1, "name": "test"}]
struct Movie: Codable, Hashable {
    let id: Int
    let name: String
}
AF.request("http://localhost/request", parameters: parameters)
    .responseDecodable(of: [Movie].self) { response in
       debugPrint(response)
    }

Upvotes: 1

Views: 2833

Answers (2)

Janou
Janou

Reputation: 155

You will need to first assign a variable to accept the JSON data. From there, you can display the result. To illustrate:

       AF.request("http://localhost/request", parameters: parameters)
.responseDecodable(of: [Movie].self) { response in
                
        let myresult = try? JSON(data: response.data!)

then print it:

        debugPrint(myresult)

If your JSON data is sound, then you should have no problem receiving the data. If your JSON is nested, then, you can drill-down into it:

           let myresult = try? JSON(data: response.data!)
           let resultArray = myresult!["result"]

and so on.

As for the "KeyNotFound" error ... It's because of what you said ... it's looking for a dictionary key/value pair. That should be resolved once you try the above example. Also, it's good practice to place your "method" in your AF request. :)

Upvotes: 2

Jon Shier
Jon Shier

Reputation: 12770

According to the error, your JSON didn't return a name value, so check that's it's actually supposed to be that key, or mark the value as optional if it's not always returned. let name: String?

Upvotes: 0

Related Questions