I'm attempting to get some data from an API and when printing the results, I keep running into this error:
typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "response", intValue: nil)], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))
These are the structs
struct Status: Decodable {
let status: String
let response: [Response]
}
struct Response: Decodable {
let docs: [Doc]
}
struct Doc: Decodable {
let webUrl: String
let abstract: String
enum CodingKeys: String, CodingKey {
case webUrl = "web_url"
case abstract
}
init(from decoder:Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
abstract = try container.decode(String.self, forKey: .abstract)
webUrl = try container.decode(String.self, forKey: .webUrl)
}
}
And I call fetchData
in my viewDidLoad
, then my array var storyData = [Doc]()
is populated with the results:
fetchData(url: jsonUrl) { (result: FetchResult<Status>) in
switch result {
case .success(let object): self.storyData = object.response.flatMap{$0.docs}
print("Results \n\n\n\n \(object.response.flatMap{$0.docs})")
case .failure(let error): print(error)
}
}
I'm not sure what to change here to get this to work. I've tried using quicktype.io to compare my code and I have my structs set up almost exactly the same way as it's generated there. This is what's generated on that site, for reference: https://app.quicktype.io?share=GGomMYH27NtkVpxXiAxB
I've checked out this question and from the solution posted by @vadian I gather that, in my case, the JSON member response
is a dictionary and docs
is an array of dictionaries - however I'm confused because an array of dictionaries is still an array, right? Also based off of his solution, I'm decoding the initial struct Status
, and then through that accessing the response
and finally getting what I need in docs
:
self.storyData = object.response.flatMap{$0.docs}
How else can I approach this to get rid of the error?