Swift Error- keyNotFound(CodingKeys(stringValue:, intValue:



我正在尝试从此API JSON文件中读取康涅狄格州冠状病毒数据-"https://data.ct.gov/resource/rf3k-f8fg.json"(但是我从excode中收到此错误,该代码显示keyNotFound(CodingKeys(stringValue:"covid19TestsReported",intValue:nil(,Swift.DecodingError.Context

但是,此错误仅在我尝试访问文件的covid_19_tests_reported属性时才会出现。

这是我的代码,有人可以告诉我我做错了什么。

import UIKit

class StateViewController: UIViewController {

@IBOutlet weak var testRatioLbl: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
getData()
}
fileprivate func getData(){
let url = URL(string: "https://data.ct.gov/resource/rf3k-f8fg.json")!
URLSession.shared.dataTask(with: url){(data, response, error) in
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let users = try decoder.decode([Users].self, from: data!)
print(users)


}
catch {
print(error)
}

}.resume()
}
func didUpdatePrice(tests: String) {

DispatchQueue.main.async {
self.testRatioLbl.text = tests + " tests"
}
}
func didFailWithError(error: Error) {
print(error)
}
}
class Users: Decodable {
let covid19TestsReported: String
enum CodingKeys: String, CodingKey {
case covid19TestsReported = "covid19TestsReported"
}
required init(from decoder:Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
covid19TestsReported = try values.decode(String.self, forKey: .covid19TestsReported)
}

}

更新你的类..你的键值是"covid_19_tests_reported"而不是"covid19TestsReported

因为此字段在某些情况下为 nil,因此使其成为可选字段

struct Users: Decodable {
let covid19TestsReported: String?
private  enum CodingKeys: String, CodingKey {
case covid19TestsReported = "covid_19_tests_reported"
}
}

同时更新您的获取数据

fileprivate func getData(){
let url = URL(string: "https://data.ct.gov/resource/rf3k-f8fg.json")!
URLSession.shared.dataTask(with: url){(data, response, error) in
do {
let decoder = JSONDecoder()
let users = try decoder.decode([Users].self, from: data!)
users.forEach { (user) in
if let cases = user.covid19TestsReported {
print(cases)
}
}
}
catch {
print(error)
}

}.resume()
}

相关内容

  • 没有找到相关文章

最新更新