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
}
提前感谢您的帮助!
解决方案
这里有两点值得一提
- 您尝试解析的响应应该来自 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)
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
}
推荐阅读
- javascript - 我正在尝试编写将单词列表淡入网页的 jQuery / JavaScript 代码
- php - 如何在php中的数组中传递多个函数参数?
- angular - 离子标签更改内容而不是所有页面
- spring - 在@EntityListeners 执行期间将实体添加到外部事务
- windows - 使用 icacls 命令设置完整性级别时,它会给出拒绝访问错误?
- c# - C# FileInfo 和并发修改?
- python - 谁能教我如何将第二个打印值写入文件?
- encryption - PGP加解密用BouncyCastle v1.8.6
- project - 排序算法项目
- php - 单选值列在 Laravel 的数据库中为空