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

Swi*_*yJD 6 json ios swift swift4 decodable

我正在尝试使用swift 4来解析本地json文件:

{
    "success": true,
    "lastId": null,
    "hasMore": false,
    "foundEndpoint": "https://endpoint",
    "error": null
}
Run Code Online (Sandbox Code Playgroud)

这是我正在使用的功能:

    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")}
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但我一直收到错误:

致命错误:Dictionary不符合Decodable,因为Any不符合Decodable.

我尝试在此stackoverflow页面上使用"AnyDecodable"方法:如何在Swift 4可解码协议中解码具有JSON字典类型的属性, 但它跳转到'catch'语句: catch { print("Local JSON not loaded")使用时.有谁知道如何在Swift 4中解析这个JSON数据?

vad*_*ian 4

也许您误解了如何Codable工作。它基于具体类型。Any不支持。

在你的情况下,你可以创建一个类似的结构

struct Something: Decodable {
    let success : Bool
    let lastId : Int?
    let hasMore: Bool
    let foundEndpoint: URL
    let error: String?
}
Run Code Online (Sandbox Code Playgroud)

并解码 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)
}
Run Code Online (Sandbox Code Playgroud)

任何崩溃都会暴露出设计错误。null在主包中的文件中使用的意义是另一个问题。