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

如何在Swift中使用对象数组解析JSON文件?

如何解决如何在Swift中使用对象数组解析JSON文件?

几个小时以来,我一直试图用数组解析为JSON文件以尝试API,但我一直遇到错误。我设法仅用一个JSON对象/字典来解析文件(遵循不同的教程),但是对于包含对象数组的JSON文件,我无法弄清楚。我正在使用冠状病毒API进行测试。这是URL,因此您可以看到JSON代码https://coronavirus-19-api.herokuapp.com/countries。我觉得解决方案很简单,只是缺少一些小东西,但我不确定。

这是我得到的错误

valueNotFound(Swift.Int,Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 10",intValue: 10),CodingKeys(stringValue: "recovered",intValue: nil)],debugDescription: "Expected Int value but found null instead.",underlyingError: nil))

这是我的代码

import UIKit

class FirstViewController: UIViewController {
    
    var coronaInfo = [CoronaInfo]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let url = "https://coronavirus-19-api.herokuapp.com/countries"
        
        getData(from: url) { (data) in
            self.coronaInfo = data
            print(self.coronaInfo[0].cases)   // <-- Works in here
        }
        
        print(coronaInfo[0].cases) // <-- Outside of the closure it's nil
    }
    
    func getData(from url: String,completed: @escaping ([CoronaInfo]) -> ()) {
        URLSession.shared.dataTask(with: URL(string: url)!) { data,response,error in
            // Make sure that data isn't nil and that there was no error
            guard let data = data,error == nil else { print("Something went wrong"); return }
            
            var result: [CoronaInfo]?
            do {
                // Convert data from bytes to the custom object (KNown as JSON decoding)
                result = try JSONDecoder().decode([CoronaInfo].self,from: data)
                
                guard let json = result else { return }
                
                dispatchQueue.main.async {
                    completed(json)
                }
            } catch { print(error) }
            
        }.resume()
    }

}

struct CoronaInfo: Codable {
    let country: String
    let cases: Int
    let todayCases: Int
    let deaths: Int
    let todayDeaths: Int
    let recovered: Int?
    let active: Int?
    let critical: Int
    let casesPerOneMillion: Int
    let deathsPerOneMillion: Int
    let totalTests: Int
    let testsPerOneMillion: Int
}

在此先感谢您的帮助!

解决方法

这里有两点值得一提

  1. 您尝试解析的响应应该来自https://coronavirus-19-api.herokuapp.com/countries,而不是https://corona-virus-stats.herokuapp.com/api/v1/cases/general-stats。因此,请使用第一个链接而不是第二个链接。
        let url = "https://coronavirus-19-api.herokuapp.com/countries"
        getData(from: url)
  1. 由于存在两个带有null值的字段,因此在模型中将其标记为可选。 enter image description here
struct CoronaData: Codable {
    let country: String
    let cases: Int
    let todayCases: Int
    let deaths: Int
    let todayDeaths: Int
    let recovered: Int?
    let active: Int?
    let critical: Int
    let casesPerOneMillion: Int
    let deathsPerOneMillion: Int
    let totalTests: Int
    let testsPerOneMillion: Int
}

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