我得到以下错误:

无法读取数据,因为它已丢失.

When I run the following code:

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)
    }

These are in a function, but I have removed them for clarity. I have a code block which is very similar in a different file (I copied this code from there and changed the names essentially) so I'm not sure why it's happening. The json file is valid json and has it's target properly set.

Thanks

推荐答案

I just solved a similar issue on my end but for the property list decoder.

本例中的错误似乎意味着没有找到密钥,而不是整个数据.

Try making the variables in your struct optional,则它应该在问题所在处返回零值.

Json相关问答推荐

Jolt转换问题—使用键查找匹配对象

如何获取brew list作为JSON输出

在ConvertFrom-Json之后需要从PowerShell对象中获取数据

无法使用Jolt变换在嵌套的JSON中提取值

匹配来自不同数组的值

使用jq根据对象中键的值查找对象

使用 jq 和脚本 bash 映射两个 json

如何使用 Google 表格应用程序脚本将 JSON 中的多个字段提取到 Google 表格中

shell解析json并循环输出组合变量

如何在 powerapps 中将详细信息表单转换为 json?

Kotlin Android Room 处理 Moshi TypeConverter 中的空对象列表

使用基本身份验证通过 CURL 发布 JSON

从 JSON 对象中删除键值对

以 unicode 将 pandas DataFrame 写入 JSON

使用 ajax 将 JSON 发送到 PHP

Sequelize - 如何仅返回数据库结果的 JSON 对象?

如何转换为 D3 的 JSON 格式?

请求返回字节,我无法解码它们

使用 axios 在 POST multipart/form-data 请求中发送文件和 json

如何遍历 JSON 中的条目?