微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Swift 中解码 JSON 时控制台没有显示任何内容

如何解决在 Swift 中解码 JSON 时控制台没有显示任何内容

我正在尝试使用 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)
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。