解码 Swift 中的 JSON 个词典 - "Expected to decode String but found a dictionary instead"
Decoding JSON dictionaries in Swift - "Expected to decode String but found a dictionary instead"
我是 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 中的 this extension 来解码 JSON。
当我打电话时:
let actors = Bundle.main.decode([String: String].self, from: "actors.json")
我收到这个错误:
“由于类型不匹配,未能从包中解码 actors.json – 预期解码数组但找到了一个字典。”
我觉得我缺少一些简单的东西。关于我在这里遗漏的任何想法?
如果您有这样的 JSON,则可以使用 let actors = Bundle.main.decode([String: String].self, from: "actors.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")
我是 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 中的 this extension 来解码 JSON。
当我打电话时:
let actors = Bundle.main.decode([String: String].self, from: "actors.json")
我收到这个错误:
“由于类型不匹配,未能从包中解码 actors.json – 预期解码数组但找到了一个字典。”
我觉得我缺少一些简单的东西。关于我在这里遗漏的任何想法?
如果您有这样的 JSON,则可以使用 let actors = Bundle.main.decode([String: String].self, from: "actors.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")