Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"Expected to decode Array<Any> but found a dictionary instead."

I am trying to fetch information from a JSON file, here are the contents of it
{ "question" : "https://www.sanfoh.com/uob/smile/data/s117b97da1ca0c9cbd2836d8af2n886.png" , "solution" : 6 }

However I am getting this error every time I try to fetch information from it
"typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary instead.", underlyingError: nil))"

Here is my code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

`

import Foundation

struct Game: Hashable, Codable {
    let question: String
    let solution: Int
}

class ViewModel: ObservableObject {
    @Published var games: [Game] = []
    
    func fetch() {
        guard let url = URL(string: "https://marcconrad.com/uob/smile/api.php") else {
            return
        }
        
        let task = URLSession.shared.dataTask(with: url) { [weak self] data, _, error in
            guard let data = data, error == nil else {
                return
            }
            
            do {
                let games = try JSONDecoder().decode([Game].self, from: data)
                DispatchQueue.main.async {
                    self?.games = games
                    print(games)
                }
            }
            catch {
                print(error)
            }
        }
        task.resume()
    }
}

`

I have tried removing the square brackets

`

                let games = try JSONDecoder().decode(Game.self, from: data)

`

however I then get an error on this line
`

                    self?.games = games

`

The error is "Cannot assign value of type ‘Game’ to type ‘[Game]’

>Solution :

The response is not an array, it is a dictionary.
So you should parse it this way:

let games = try JSONDecoder().decode(Game.self, from: data)

Also, you should update the variable’s type like

@Published var games: Game?
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading