ios - JSONDecoder 无法解码嵌套字典
问题描述
我正在使用 JSONDecoder 从具有嵌套字典的 JSON 文件中解码。它无法从 json 数据解码到我的自定义模型。
这是我在我的代码中尝试过的。
- JSONDecoder 看起来像这样:
let netWorkManager = NetWorkManager(URL: url, httpMethodType: .GET)
netWorkManager.callAPI { (data, status, error) in
guard let data = data else {
onFail(NetWorkError.otherError)
return
}
switch status {
case 200:
do{
if let responseModel = try JSONDecoder().decode(ResonseModel?.self, from: data) {
onSuccess(responseModel)
}
}catch {
onFail(NetWorkError.otherError)
}
default:
onFail(NetWorkError.otherError)
}
}
- 该模型如下所示:
struct ResonseModel: Codable {
let type : String
let format: String
let data: [String: Champion]
struct Champion: Codable {
let version: String
let id: String
let key: Int
let name: String
let title: String
let blurb: String
}
}
- JSON 结构如下所示:
{
"type": "champion",
"format": "standAloneComplex",
"version": "9.3.1",
"data": {
"Aatrox": {
"version": "9.3.1",
"id": "Aatrox",
"key": "266",
"name": "Aatrox",
"title": "the Darkin Blade",
"blurb": "Once honored defenders of Shurima against the Void, Aatrox and his brethren would eventually become an even greater threat to Runeterra, and were defeated only by cunning mortal sorcery. But after centuries of imprisonment, Aatrox was the first to find...",
"info": {
"attack": 8,
"defense": 4,
"magic": 3,
"difficulty": 4
},
"tags": [
"Fighter",
"Tank"
],
"partype": "Blood Well",
},
"Ahri": {
"version": "9.3.1",
"id": "Ahri",
"key": "103",
"name": "Ahri",
"title": "the Nine-Tailed Fox",
"blurb": "Innately connected to the latent power of Runeterra, Ahri is a vastaya who can reshape magic into orbs of raw energy. She revels in toying with her prey by manipulating their emotions before devouring their life essence. Despite her predatory nature...",
"info": {
"attack": 3,
"defense": 4,
"magic": 8,
"difficulty": 5
},
"tags": [
"Mage",
"Assassin"
],
"partype": "Mana",
},
...
如果您想查看它,这是 JSON 的链接:http: //ddragon.leagueoflegends.com/cdn/9.3.1/data/en_US/champion.json
我想将“数据”属性解码为一个字典,其键是冠军的名字,值是冠军。但是 jsonDecoder 似乎无法识别我的模型结构。它最终捕获了错误。
解决方案
JSON 参数“key”不是整数。
将其更改为 String ,它将起作用:
struct ResonseModel: Codable {
let type : String
let format: String
let data: [String: Champion]
struct Champion: Codable {
let version: String
let id: String
let key: String
let name: String
let title: String
let blurb: String
}
}
推荐阅读
- vb.net - 检查值是否存在,如果是则更新如果不插入 ms 访问 vb.net
- azure - 如何通过rest api触发azure管道
- android - 应用程序启动后后压时出现 IllegalArgumentException
- python - 圆角 QFrame 中的溢出小部件
- java - 使用 DataInputStream 和 DataOutputStream 发送和 int 时出现 nullPointerException
- python-3.x - AttributeError:模块'os'在ubuntu 16.04上的命令virutalenv mydir之后没有属性'PathLike'
- javascript - 在 Javascript 中重构 double for 循环
- node.js - 无法在 heroku 上部署我的 MERN 堆栈应用程序
- php - 创建记录时,Mysql 触发器将 id 从一列复制到同一表中的另一列
- python - 赋值没有按预期工作