ios - "The data couldn’ t be read because it is missing”在Swift中解码JSON时出错

标签 ios json swift

我收到以下错误:

无法读取数据,因为它丢失了。

当我运行以下代码时:

struct Indicator: Decodable {
    let section: String
    let key: Int
    let indicator: Int
    let threshold: Int
}
    var indicators = [Indicator]()

    do {
        if let file = Bundle.main.url(forResource: "indicators", withExtension: "json") {
            indicators = try JSONDecoder().decode([Indicator].self, from: try Data(contentsOf: file))
        }
    } catch {
        print(error.localizedDescription)
    }

这些在一个函数中,但为了清楚起见我已经删除了它们。我有一个代码块,它在另一个文件中非常相似(我从那里复制了这段代码并基本上更改了名称)所以我不确定为什么会这样。 json 文件是有效的 json 并且目标设置正确。

谢谢

最佳答案

打印 error.localizedDescription 具有误导性,因为它仅显示毫无意义的通用错误消息。

所以永远不要在Decodable catch block 中使用localizedDescription

简单的形式就是

print(error)

它显示了完整的错误,包括关键信息 debugDescriptioncontextDecodable 错误非常全面。


例如,在开发代码时,您可以分别捕获每个 Decodable 错误

} catch let DecodingError.dataCorrupted(context) {
    print(context)
} catch let DecodingError.keyNotFound(key, context) {
    print("Key '\(key)' not found:", context.debugDescription)
    print("codingPath:", context.codingPath)
} catch let DecodingError.valueNotFound(value, context) {
    print("Value '\(value)' not found:", context.debugDescription)
    print("codingPath:", context.codingPath)
} catch let DecodingError.typeMismatch(type, context)  {
    print("Type '\(type)' mismatch:", context.debugDescription)
    print("codingPath:", context.codingPath)
} catch {
    print("error: ", error)
}

它只显示最重要的信息。

关于ios - "The data couldn’ t be read because it is missing”在Swift中解码JSON时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46959625/

相关文章:

javascript - Asp.Net MVC 3 formcollection在提交后丢失数据

ios - 使用导航 Controller 时滞后 UITableView 滚动

iphone - 如何使用 MailCore 定期获取新邮件

java - 比较具有相同 .toString 内容的 JSONObject 和 Object

ios - 播放视频时未调用 UITableView didEndDisplaying

JQuery.ajax 适用于除 IE 之外的所有平台

ios - Twilio videoView 委托(delegate)未调用

ios - 用于将 Single<[Element]> 转换为 Observable<Element> 的 rxSwift 扩展

IOS 将 2 个 GMSMarkers 之间的箭头线绘制到 Google map 中

ios - Spika-iOS : "incompatible block pointer types"