[英]Fatal error: Dictionary<String, Any> does not conform to Decodable because Any does not conform to Decodable
我正在嘗試使用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")}
}
}
}
但我一直收到錯誤:
致命錯誤:Dictionary不符合Decodable,因為Any不符合Decodable。
我嘗試在此stackoverflow頁面上使用“AnyDecodable”方法: 如何在Swift 4可解碼協議中解碼具有JSON字典類型的屬性,但它跳轉到'catch'語句: catch { print("Local JSON not loaded")
when正在使用。 有誰知道如何在Swift 4中解析這個JSON數據?
也許你誤解了Codable
工作原理。 它基於具體類型。 Any
不受支持。
在您的情況下,您可以創建一個類似的結構
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
的意義是另一個問題。
我使用quicktype生成Codables和編組代碼:
https://app.quicktype.io?gist=02c8b82add3ced7bb419f01d3a94019f&l=swift
我根據您的樣本數據給出了一系列樣本:
[
{
"success": true,
"lastId": null,
"hasMore": false,
"foundEndpoint": "https://endpoint",
"error": null
},
{
"success": true,
"lastId": 123,
"hasMore": false,
"foundEndpoint": "https://endpoint",
"error": "some error"
}
]
這告訴quicktype假設第一個樣本中的null
值有時是Int
和String
- 如果它們不是可能的類型,則可以更改它們。 生成的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.