I am trying to decode this json but it keep failing on "failed to decode" line. I validated the json, checked the struct, these looks fine to me. Am i misssing something?
JsonManager.swift
extension Bundle {
func decode (_ file: String) -> Cities {
guard let url = self.url(forResource: file, withExtension: nil) else {
fatalError("Failed to locate \(file) in bundle")
}
guard let data = try? Data(contentsOf: url) else {
fatalError("failed to load \(file) bundle")
}
let decoder = JSONDecoder()
guard let loaded = try? decoder.decode(Cities.self, from: data) else {
fatalError("Failed to decode \(file) from bundle")
// (Run time error here) Fatal error: Failed to decode cities.json from bundle
}
print("loaded")
return loaded
}
}
ContentView.swift
var cities = Bundle.main.decode("cities.json")
cities.json
{
"city": [
{
"id": "1",
"name": "Mumbai",
"state": "Maharashtra"
},
{
"id": "2",
"name": "Delhi",
"state": "Delhi"
}
]
}
JsonStruct.swift
struct Cities: Codable {
struct City: Codable {
let id: String
let name: String
let state: String
}
let city: [City]
}