Search code examples
iosarraysjsonswiftdecode

JSON API - Stuck with "Expected to decode Array<Any> but found a dictionary instead


Generally fairly ok with using decodable etc now but this one is really sticking me. I have an API that returns the following response

{
    "data": {
        "contentResults": [{
            "id": 2,
            "title": "news report 1",
            "imageUrl": "www.image.com"
        }, {
            "id": 1,
            "title": "news report 2",
            "imageUrl": "www.image.com"
        }]
    }
}

What is tripping me up is the array inside the data object I can't seem to get it to decode properly.

This is my structs for decoding

struct TopLevel: Codable { 

    let contentResults: [contentResults]

    

    enum CodingKeys: String, CodingKey {

        case contentResults

    }

}



struct contentResults: Codable {

    public var title: String

    public var imageUrl: String

    

    enum CodingKeys: String, CodingKey {

        case title = "title"

        case imageUrl = "imageUrl"

    }

}

Xcode keeps giving me the error "Expected to decode Array but found a dictionary instead" which I do know what it means but I have banged my head against the wall for a few hours now on this one so would like some help. I have referenced this particular page https://stackoverflow.com/questions/63527849/swift-decoding-expected-to-decode-arrayany-but-found-a-dictionary-instead and whilst it helped me a little it did not get me over the line

Any help appreciated. cheers


Solution

  • you are missing the part of parsing "data":

    struct DataResponse: Codable {
    let data: TopLevel 
    }