【发布时间】:2021-08-29 20:34:37
【问题描述】:
我收到以下错误:
数据丢失,无法读取。
当我运行以下代码时:
var p = [Prevalentie]()
let url = URL(string: "https://data.rivm.nl/covid-19/COVID-19_prevalentie.json")!
let task = URLSession.shared.dataTask(with: url) {
(data: Data?, response: URLResponse?, error: Error?) -> Void in
if let jsonData = data
{
let decoder = JSONDecoder()
do {
p = try decoder.decode([Prevalentie].self, from: jsonData)
print(p)
} catch {
print(error.localizedDescription)
}
}
DispatchQueue.main.async {
}
struct Prevalentie:Codable {
var Date:String
var prev_avg:Int
}
The json data:
{"Date":"2020-02-17","prev_low":693,"prev_avg":1067,"prev_up":1425,"population":"hosp","version":1}
我可以得到 date 的值,但不能得到 prev_avg。我该如何解决这个问题? 谢谢,
【问题讨论】:
-
打印
error而不是error.localizedDescription。它会准确地告诉你出了什么问题。 -
如前所述,打印
error而不是error.localizedDescription,同时显示您使用JSONDecoder的代码。 -
我收到“无法读取数据,因为它丢失了。”错误
-
不,如果你这样做
print(error.localizedDescription)=>print(error),你会在控制台中得到不同的输出!然后修复将是decode([Prevalentie].self=>decode(Prevalentie.self。 -
读取错误。数组中的第 474 个元素没有
prev_avg值。