debugDescription:“预期解码阵列< Any>".但是找到了字典.",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: 打算对Array进行解码,但是找到了一个字典.", 底层错误: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的开头
First take a look at the beginning of the 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.
但这只是解决方案的一半.将行更改为try decoder.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并将键与struct成员进行比较.成员与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:“预期解码阵列< Any>".但是找到了字典.",underlyingError:nil)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!