【发布时间】:2018-08-07 16:09:26
【问题描述】:
我正在尝试使用 swift 4 解析本地 json 文件:
{
"success": true,
"lastId": null,
"hasMore": false,
"foundEndpoint": "https://endpoint",
"error": null
}
这是我正在使用的功能:
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")}
}
}
}
但我不断收到错误:
致命错误:字典不符合 Decodable 因为 Any 不符合 Decodable。
我尝试在此 stackoverflow 页面上使用“AnyDecodable”方法:How to decode a property with type of JSON dictionary in Swift 4 decodable protocol
但它在使用时会跳转到“catch”语句:catch { print("Local JSON not loaded")。有谁知道如何在 Swift 4 中解析这个 JSON 数据?
【问题讨论】:
标签: ios json swift swift4 decodable