json - Swift:找不到密钥 JSON 解码
问题描述
我正在尝试从以下网站解码 JSON 对象:https ://www.thesportsdb.com/api/v1/json/1/search_all_leagues.php?c=France&s=Soccer
我想将它们存储在一组足球元素中,并在单元格中显示它们。
这是我做的代码,但是我没有找到密钥错误,这怎么可能?
class Soccer: Codable {
var strLeague: String
var strDescriptionEN: String
var strBadge: String
var strDivision: String
var intFormedYear: String
var strCountry: String
init(strLeague: String, strDescriptionEN: String, strBadge: String, strDivision: String, intFormedYear: String, strCountry: String) {
self.strLeague = strLeague
self.strDescriptionEN = strDescriptionEN
self.strBadge = strBadge
self.strDivision = strDivision
self.intFormedYear = intFormedYear
self.strCountry = strCountry
}
}
class SoccerTVC: UITableViewController {
var leagues = [Soccer]()
func download(at url: String, handler: @escaping (Data?) -> Void)
{
// 1 - Create URL
guard let url = URL(string: url) else {
debugPrint("Failed to create URL")
handler(nil)
return
}
// 2 - Create GET Request
var request: URLRequest = URLRequest(url: url)
request.httpMethod = "GET"
// 3 - Create download task, handler will be called when request ended
let task = URLSession.shared.dataTask(with: request) {
(data, response, error) in handler(data)
}
task.resume()
}
func getSoccer() {
// 1 - Download Soccer
download(at: "https://www.thesportsdb.com/api/v1/json/1/search_all_leagues.php?c=France&s=Soccer")
{ (SoccerData) in
if let Soccerdata = SoccerData {
// 2 - Decode JSON into a array of Game object
let decoder: JSONDecoder = JSONDecoder()
do {
let jsonData = [try decoder.decode(Soccer.self, from: Soccerdata)]
self.leagues = jsonData
debugPrint(self.leagues)
DispatchQueue.main.sync {
self.tableView.reloadData()
}
}
catch {
debugPrint("Failed to parse data - error: \(error)")
}
}
else
{
debugPrint("Failed to get soccer data")
}
}
}
override func viewDidLoad() {
getSoccer()
super.viewDidLoad()
}
}
错误信息:
无法解析数据 - 错误:keyNotFound(CodingKeys(stringValue: "strLeague", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"strLeague\" , intValue: nil) (\"strLeague\").", 基础错误: nil))
解决方案
试试这个:
let jsonData = try JSONDecoder().decode([String:[Soccer]].self, from: Soccerdata)
self.leagues = jsonData.values
推荐阅读
- javascript - 从 Vue JS 中的 URL 获取参数
- google-maps - 如何使用 Chrome 意图打开谷歌地图应用程序并开始导航?
- kotlinx.serialization - 类“TaskPayload”未在“EventPayload”范围内注册多态序列化
- elasticsearch - Elasticsearch Match 查询分析文本字段中的所有单词
- entity-framework-core - EF Core - 更改跟踪子记录
- node.js - 如何在 TypeORM 中正确插入具有 OneToMany 关系的实体
- spring-security - Okta Spring - 如何故意覆盖 401 并重定向到 404
- javascript - 迁移 GoogleSheets - 新 API
- php - 使用php分页时隐藏用户ID
- javascript - 使用 jQuery 和 .css 创建一个由 6 个图像组成的完美环