I'm new to Swift and programming. I am having some trouble decoding a JSON file.
I have JSON that looks like:
{
"actors": {
"2048": "Gary Busey",
"3": "Harrison Ford",
"5251": "Jack Warden",
"14343": "Rene Russo",
"51214": "Brad Renfro",
"9560": "Ellen Burstyn"
}
}
My model is:
struct Actors: Codable {
let actors: [String: String]
}
I'm using this extension from hackingwithswift.com to decode the JSON.
When I call:
let actors = Bundle.main.decode([String: String].self, from: "actors.json")
I get this error:
"Failed to decode actors.json from bundle due to type mismatch – Expected to decode Array but found a dictionary instead."
I feel like I am missing something simple. Any ideas on what I am missing here?
CodePudding user response:
Decoding with let actors = Bundle.main.decode([String: String].self, from: "actors.json")
would work if you had a JSON like this:
{
"2048": "Gary Busey",
"3": "Harrison Ford",
"5251": "Jack Warden",
"14343": "Rene Russo",
"51214": "Brad Renfro",
"9560": "Ellen Burstyn"
}
But you have additionally a dictionary with a string key and a dictionary value. Try this:
let actors = Bundle.main.decode([[String: [String: String]].self, from: "actors.json")
Or this:
let actors = Bundle.main.decode(Actors.self, from: "actors.json")