Ad

Faild To Decode JSON, SwiftUI

- 1 answer

I can’t seem to decode my JSON. It locates, and loads, but fails to decode.

Here is the JSON example:

[{
"name": "Hartsfield Jackson Atlanta Intl",
"city": "Atlanta",
"country": "United States",
"iata_code": "ATL",
"_geoloc": {
  "lat": 33.636719,
  "lng": -84.428067
},
"links_count": 1826,
"objectID": "3682"}]

Here is my Struct:

struct Airports: Codable, Identifiable {
struct GeoLoc: Codable {
    let lat: Double
    let lng: Double
}
var id = UUID()
let name: String
let city: String
let country: String
let iata_code: String
let _geoloc: GeoLoc
let links_count: Int
let objectID: String }

Bundle etension:

extension Bundle {
func decode<T: Codable>(_ file: String) -> T {
    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) from bundle.")
    }
    
    let decoder = JSONDecoder()
    let formatter = DateFormatter()
    formatter.dateFormat = "y-MM-dd"
    decoder.dateDecodingStrategy = .formatted(formatter)
    
    guard let loaded = try? decoder.decode(T.self, from: data) else {
        fatalError("Failed to decode \(file) from bundle.")
    }
    
    return loaded
}}

And I call it in my content View like this:

let airports: [Airports] = Bundle.main.decode("airports.json")

I get the fatalError("Failed to decode (file) from bundle.") So my question is, what is wrong here? Is the mistake in my Airport Struct? I know the bundle extension is working, I have used the same with many other JSONS.

Ad

Answer

It is beacuse of property of id in your structure your json has no key id and id in structure is not optional. You have to change it with

let id : UUID?

instead of

var id = UUID()
Ad
source: stackoverflow.com
Ad