我是 Swift 和編程的新手。我在解碼 JSON 檔案時遇到了一些問題。
我的 JSON 看起來像:
{
"actors": {
"2048": "Gary Busey",
"3": "Harrison Ford",
"5251": "Jack Warden",
"14343": "Rene Russo",
"51214": "Brad Renfro",
"9560": "Ellen Burstyn"
}
}
我的模型是:
struct Actors: Codable {
let actors: [String: String]
}
我正在使用來自 hackingwithswift.com 的擴展來解碼 JSON。
當我打電話時:
let actors = Bundle.main.decode([String: String].self, from: "actors.json")
我收到此錯誤:
“由于型別不匹配,無法從 bundle 中解碼 actor.json - 預期解碼 Array 但找到了字典。”
我覺得我錯過了一些簡單的東西。關于我在這里缺少什么的任何想法?
uj5u.com熱心網友回復:
let actors = Bundle.main.decode([String: String].self, from: "actors.json")如果您有這樣的 JSON ,使用解碼將起作用:
{
"2048": "Gary Busey",
"3": "Harrison Ford",
"5251": "Jack Warden",
"14343": "Rene Russo",
"51214": "Brad Renfro",
"9560": "Ellen Burstyn"
}
但是您還有一個帶有字串鍵和字典值的字典。嘗試這個:
let actors = Bundle.main.decode([[String: [String: String]].self, from: "actors.json")
或這個:
let actors = Bundle.main.decode(Actors.self, from: "actors.json")
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/441315.html
上一篇:swiftcombine中兩個如何處理異步呼叫中的錯誤?
下一篇:從存盤的拋出函式中拋出錯誤
