我收到以下错误:
无法读取数据,因为它丢失了。
当我运行以下代码时:
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)
它显示了完整的错误,包括关键信息 debugDescription
和 context
。Decodable
错误非常全面。
例如,在开发代码时,您可以分别捕获每个 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/