简体   繁体   English

致命错误:字典 <String, Any> 不符合Decodable,因为Any不符合Decodable

[英]Fatal error: Dictionary<String, Any> does not conform to Decodable because Any does not conform to Decodable

I'm trying to use swift 4 to parse a local json file: 我正在尝试使用swift 4来解析本地json文件:

{
    "success": true,
    "lastId": null,
    "hasMore": false,
    "foundEndpoint": "https://endpoint",
    "error": null
}

This is the function I'm using: 这是我正在使用的功能:

    func loadLocalJSON() {

        if let path = Bundle.main.path(forResource: "localJSON", ofType: "json") {
            let url = URL(fileURLWithPath: path)

            do {
                let data  = try Data(contentsOf: url)
                let colors = try JSONDecoder().decode([String: Any].self, from: data)
                print(colors)
            }
            catch { print("Local JSON not loaded")}
        }
    }
}

but I keep getting the error: 但我一直收到错误:

Fatal error: Dictionary does not conform to Decodable because Any does not conform to Decodable. 致命错误:Dictionary不符合Decodable,因为Any不符合Decodable。

I tried using the "AnyDecodable" approach on this stackoverflow page: How to decode a property with type of JSON dictionary in Swift 4 decodable protocol but it jumps to the 'catch' statement: catch { print("Local JSON not loaded") when being used. 我尝试在此stackoverflow页面上使用“AnyDecodable”方法: 如何在Swift 4可解码协议中解码具有JSON字典类型的属性,但它跳转到'catch'语句: catch { print("Local JSON not loaded") when正在使用。 Does anyone know how to parse this JSON data in Swift 4? 有谁知道如何在Swift 4中解析这个JSON数据?

Maybe you are misunderstanding how Codable works. 也许你误解了Codable工作原理。 It's based on concrete types. 它基于具体类型。 Any is not supported. Any不受支持。

In your case you might create a struct like 在您的情况下,您可以创建一个类似的结构

struct Something: Decodable {
    let success : Bool
    let lastId : Int?
    let hasMore: Bool
    let foundEndpoint: URL
    let error: String?
}

And decode the JSON 并解码JSON

func loadLocalJSON() {
    let url = Bundle.main.url(forResource: "localJSON", withExtension: "json")!
    let data  = try! Data(contentsOf: url)
    let colors = try! JSONDecoder().decode(Something.self, from: data)
    print(colors)
}

Any crash will reveal a design error. 任何崩溃都会显示设计错误。 The sense of using null in a file in the main bundle is another question. 在主包中的文件中使用null的意义是另一个问题。

I used quicktype to generate Codables and marshaling code: 我使用quicktype生成Codables和编组代码:

https://app.quicktype.io?gist=02c8b82add3ced7bb419f01d3a94019f&l=swift https://app.quicktype.io?gist=02c8b82add3ced7bb419f01d3a94019f&l=swift

I gave it an array of samples based on your sample data: 我根据您的样本数据给出了一系列样本:

[
  {
    "success": true,
    "lastId": null,
    "hasMore": false,
    "foundEndpoint": "https://endpoint",
    "error": null
  },
  {
    "success": true,
    "lastId": 123,
    "hasMore": false,
    "foundEndpoint": "https://endpoint",
    "error": "some error"
  }
]

This tells quicktype to assume that the null values in your first sample are sometimes Int and String – you can change these if they aren't the possible types. 这告诉quicktype假设第一个样本中的null值有时是IntString - 如果它们不是可能的类型,则可以更改它们。 The resulting Codable generated is: 生成的Codable是:

struct Local: Codable {
    let success: Bool
    let lastID: Int?
    let hasMore: Bool
    let foundEndpoint: String
    let error: String?

    enum CodingKeys: String, CodingKey {
        case success
        case lastID = "lastId"
        case hasMore, foundEndpoint, error
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Swift:任何数组不符合“可解码”协议 - Swift: Array of any does not conform to protocol 'Decodable' 不符合协议可解码 - Does not conform to protocol Decodable 不符合协议 'Decodable' 和 'Encodable' - does not conform to protocol 'Decodable' and 'Encodable' 类型“ MenuItem”不符合协议“可解码” - Type 'MenuItem' does not conform to protocol 'Decodable' 类型“PlayerData”不符合协议“Decodable”和“Encodable” - Type 'PlayerData' does not conform to protocol 'Decodable' and 'Encodable' 自定义结构:类型不符合“可解码”协议 - Custom Struct: Type does not conform to protocol 'Decodable' 类型“模型”不符合协议“可解码”/可编码 - Type 'Model' does not conform to protocol 'Decodable'/Encodable Swift Codable:无法解码 [String: Any] 或 [String: Decodable] 类型的字典 - Swift Codable: Cannot decode dictionary of type [String: Any] or [String: Decodable] swift 将字典转换为 jsonString 错误:协议类型 'Any' 不能符合 'Encodable' 因为只有具体类型才能符合协议 - swift Convert dictionary to jsonString error : Protocol type 'Any' cannot conform to 'Encodable' because only concrete types can conform to protocols DictionaryLiteral &lt;_,_&gt;类型的值在强制上不符合&#39;Any&#39; - Value of type DictionaryLiteral<_,_> does not conform to 'Any' in coersion
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM