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

Time:11-09

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

`

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]'

CodePudding user response:

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?
  • Related