debugDescription:“预期解码数组<任何>"但找到了一本字典.",underlyingError: nil) [英] debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil)
问题描述
我想将一个在线 json 文件加载到我的应用程序中,但我遇到了这个错误:
I want to load an online json file into my application, but I am running into this error:
typeMismatch(Swift.Array,Swift.DecodingError.Context(codingPath: [], debugDescription:"本应解码数组,但找到了字典.",底层错误:nil))
typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary instead.", underlyingError: nil))
我查看了 stackoverflow,但其他解决方案并没有帮助解决我的问题.
I have looked on stackoverflow but other sollutions didn't help to solve mine.
我的json
我的数据模型:
import Foundation
struct Initial: Codable {
let copyright: String
let totalItems: Int
let totalEvents: Int
let totalGames: Int
let totalMatches: Int
let wait: Int
let dates: [Dates]
}
struct Dates: Codable {
let date: String
let totalItems: Int
let totalEvents: Int
let totalGames: Int
let totalMatches: Int
let games: [Game]
}
struct Game: Codable {
let gamePk: Int
let link: String
let gameType: String
let season: String
let gameDate: String
let status: Status
let teams: Team
let venue: Venue
let content: Content
}
struct Status: Codable {
let abstractGameState: String
let codedGameState: Int
let detailedState: String
let statusCode: Int
let startTimeTBD: Bool
}
struct Team: Codable {
let away: Away
let home: Home
}
struct Away: Codable {
let leagueRecord: LeagueRecord
let score: Int
let team: TeamInfo
}
struct Home: Codable {
let leagueRecord: LeagueRecord
let score: Int
let team: TeamInfo
}
struct LeagueRecord: Codable {
let wins: Int
let losses: Int
let type: String
}
struct TeamInfo: Codable {
let id: Int
let name: String
let link: String
}
struct Venue: Codable {
let name: String
let link: String
}
struct Content: Codable {
let link: String
}
这是我的视图控制器
import UIKit
class TodaysGamesTableViewController: UITableViewController {
var todaysGamesURL: URL = URL(string: "https://statsapi.web.nhl.com/api/v1/schedule")!
var gameData: [Dates] = []
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
override func viewDidLoad() {
super.viewDidLoad()
loadTodaysGames()
}
func loadTodaysGames(){
print("load Games")
view.addSubview(activityIndicator)
activityIndicator.frame = view.bounds
activityIndicator.startAnimating()
let todaysGamesDatatask = URLSession.shared.dataTask(with: todaysGamesURL, completionHandler: dataLoaded)
todaysGamesDatatask.resume()
}
func dataLoaded(data:Data?,response:URLResponse?,error:Error?){
if let detailData = data{
print("detaildata", detailData)
let decoder = JSONDecoder()
do {
let jsondata = try decoder.decode([Dates].self, from: detailData)
gameData = jsondata //Hier .instantie wil doen krijg ik ook een error
DispatchQueue.main.async{
self.tableView.reloadData()
}
}catch let error{
print(error)
}
}else{
print(error!)
}
}
推荐答案
请学会理解解码错误信息,它们非常具有描述性.
Please learn to understand the decoding error messages, they are very descriptive.
错误提示您要解码数组,但实际对象是字典(目标结构).
The error says you are going to decode an array but the actual object is a dictionary (the target struct).
先看看开头的JSON
{
"copyright" : "NHL and the NHL Shield are registered trademarks of the National Hockey League. NHL and NHL team marks are the property of the NHL and its teams. © NHL 2018. All Rights Reserved.",
"totalItems" : 2,
"totalEvents" : 0,
"totalGames" : 2,
"totalMatches" : 0,
"wait" : 10,
"dates" : [ {
"date" : "2018-05-04",
它以一个 {
开头,它是一个字典(一个数组是 [
)但是你想解码一个数组([Dates]
),这是错误消息所指的类型不匹配.
It starts with a {
which is a dictionary (an array is [
) but you want to decode an array ([Dates]
), that's the type mismatch the error message is referring to.
但这只是解决方案的一半.将行更改为 trydecoder.decode(Dates.self
后,您将收到另一个错误,即没有密钥 copyright
的值.
But this is only half the solution. After changing the line to try decoder.decode(Dates.self
you will get another error that there is no value for key copyright
.
再次查看 JSON 并将键与结构成员进行比较.其成员与 JSON 键匹配的结构是 Initial
,您必须获取 dates
数组以填充 gameData
.
Look again at the JSON and compare the keys with the struct members. The struct whose members match the JSON keys is Initial
and you have to get the dates
array to populate gameData
.
let jsondata = try decoder.decode(Initial.self, from: detailData)
gameData = jsondata.dates
这篇关于debugDescription:“预期解码数组<任何>"但找到了一本字典.",underlyingError: nil)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!