我正在嘗試從 JSON 檔案中獲取資訊,這是它的內容
{ "question" : "https://www.sanfoh.com/uob/smile/data/s117b97da1ca0c9cbd2836d8af2n886.png" , "solution" : 6 }
但是,每次嘗試從中獲取資訊時,我都會收到此錯誤“typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: “Expected to decode Array but found a dictionary instead.”,underlyingError:零))”
這是我的代碼
`
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()
}
}
`
我試過洗掉方括號
`
let games = try JSONDecoder().decode(Game.self, from: data)
`
但是我在這一行得到一個錯誤`
self?.games = games
`
錯誤是“無法將型別 'Game' 的值分配給型別 '[Game]'
uj5u.com熱心網友回復:
回應不是陣列,而是字典。所以你應該這樣決議它:
let games = try JSONDecoder().decode(Game.self, from: data)
此外,您應該更新變數的型別,例如
@Published var games: Game?
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/529554.html
標籤:json迅速
