【问题标题】:“The data couldn’t be read because it is missing” error when decoding JSON in Swift在 Swift 中解码 JSON 时出现“无法读取数据,因为它丢失了”错误
【发布时间】: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 值。

标签: ios json swift


【解决方案1】:

也许您的响应对象之一具有prev_avg 参数的nil 值。 为避免此错误,请将prev_avg 参数设置为可选的ex:let prev_avg:Int?,或者如果您想处理nil 参数,请返回您的后端。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    相关资源
    最近更新 更多