问题描述
我正在尝试使用 Github 中的 COVID 数据集(下面代码中的链接),但是当我运行代码时,控制台中没有任何显示。没有出现错误。
任何人都可以就这里出了什么问题提出建议吗?提前致谢!
struct country: Decodable {
var location: String
var new_cases: Double
var people_fully_vaccinated: Double
}
func getJSON(){
guard let url = URL(string: "https://raw.githubusercontent.com/owid/covid-19-data/68c39808d445fe90b1fe3d57b93ad9be20f796d2/public/data/latest/owid-covid-latest.json") else{
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request){ (data,response,error) in
if let error = error{
print(error.localizedDescription)
return
}
guard let data = data else{
return
}
let decoder = JSONDecoder()
guard let decodedData = try? decoder.decode([country].self,from: data) else{
return
}
let countries = decodedData
for country in countries{
print (country.location)
}
}.resume()
}
getJSON()
解决方法
你需要
struct Root: Decodable {
var location: String
var new_cases: Double? // make it optional as it has some objects with nil
var people_fully_vaccinated: Double? // make it optional as it has some objects with nil
}
与
do {
let res = try decoder.decode([String:Root].self,from: data)
let locations = Array(res.values).map { $0.location }
print(locations)
}
catch {
print(error)
}