首页 > 解决方案 > 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))

标签: jsonswifterror-handlingdecodingjsondecoder

解决方案


试试这个:

let jsonData = try JSONDecoder().decode([String:[Soccer]].self, from: Soccerdata)
self.leagues = jsonData.values

推荐阅读