Swift 错误- keyNotFound(CodingKeys(stringValue:, intValue: nil), Swift.DecodingError.Context,

Swift Error- keyNotFound(CodingKeys(stringValue:, intValue: nil), Swift.DecodingError.Context,

我正在尝试从此 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)
}

}

更新你 class..你的关键值是“covid_19_tests_reported”而不是“covid19TestsReported

因为该字段在某些情况下为 nil,所以将其设为可选

 struct Users: Decodable {
    let covid19TestsReported: String?

  private  enum CodingKeys: String, CodingKey {
        case covid19TestsReported = "covid_19_tests_reported"

    }
}

同时更新您的 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()
                let users = try decoder.decode([Users].self, from: data!)

                users.forEach { (user) in
                    if let cases = user.covid19TestsReported {
                    print(cases)
                    }
                }
            }
            catch {

                print(error)
            }


        }.resume()
    }