致命错误:Dictionary< String,Any>不符合Decodable,因为Any不符合Decodable [英] Fatal error: Dictionary<String, Any> does not conform to Decodable because Any does not conform to Decodable
问题描述
我正在尝试使用swift 4解析本地json文件:
I'm trying to use swift 4 to parse a local json file:
{
"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:
致命错误:字典不符合可解码" 因为Any不符合Decodable.
Fatal error: Dictionary does not conform to Decodable because Any does not conform to Decodable.
我尝试在此stackoverflow页面上使用"AnyDecodable"方法:.有谁知道如何在Swift 4中解析此JSON数据?
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. Does anyone know how to parse this JSON data in Swift 4?
推荐答案
也许您误解了Codable
的工作方式.它基于具体类型.不支持Any
.
Maybe you are misunderstanding how Codable
works. It's based on concrete types. Any
is not supported.
在您的情况下,您可以创建类似的结构
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?
}
并解码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)
}
任何崩溃都会显示设计错误.在主捆绑包中的文件中使用null
的感觉是另一个问题.
Any crash will reveal a design error. The sense of using null
in a file in the main bundle is another question.
这篇关于致命错误:Dictionary< String,Any>不符合Decodable,因为Any不符合Decodable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!