Home > Blockchain >  Error decoding: typeMismatch , In decoding Data from a Rest API
Error decoding: typeMismatch , In decoding Data from a Rest API

Time:01-27

HIDDEN (sorry)

HIDDEN (sorry)

HIDDEN (sorry)

HIDDEN (sorry)

CodePudding user response:

try this example code to fetch, decode and display your json data. The important thing to remember is that your models need to match the json data exactly.

You will have to consult the server docs to determine which properties are optional, and adjust the code of the models by adding ? to it.

struct ContentView: View {
    var body: some View {
        TestTABTESTTEST()
    }
}

struct TestTABTESTTEST: View {
    @StateObject var jsonDataVBB = JsonDataVBB()  // <-- here
    
    var body: some View {
        NavigationView {
            VStack {
                // --- here
                List(jsonDataVBB.stationNameAPI) { item in
                    Text(item.name).foregroundColor(.blue)
                    Text("lat: \(item.lat)  lon: \(item.lon)")
                }
                .navigationBarTitle("⚠", displayMode: .inline)
                .onAppear{
                    jsonDataVBB.departureNEWOldFetch()
                }
                .refreshable {
                    jsonDataVBB.departureNEWOldFetch()
                }
            }
            .toolbarBackground(.visible, for: .navigationBar)
        }
        .toolbarBackground(.visible, for: .navigationBar)
        .toolbarBackground(.visible, for: .tabBar)
        .toolbarBackground(.visible, for: .bottomBar)
        .toolbarBackground(.visible, for: .navigationBar)
    }
}

class JsonDataVBB: ObservableObject {
    @Published var stationNameAPI = [StopLocation]()
    
    func departureNEWOldFetch() {
        let url = URL(string: "https://....")!
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            if let error = error {
                print("Error fetching departures: \(error)")
                return
            }
            guard let data = data else {
                print("No data received")
                return
            }
            do {
                // --- here
                let sucheVBB = try JSONDecoder().decode(StationSuche.self, from: data)
                DispatchQueue.main.async {
                    // --- here
                    self.stationNameAPI = sucheVBB.stopLocationOrCoordLocation.map{$0.stopLocation}
                }
            } catch let error {
                print("Error decoding departures: \(error)")
            }
        }.resume()
    }
    
}

struct StationSuche: Codable, Identifiable {
    var id = UUID()
    let stopLocationOrCoordLocation: [StopLocationOrCoordLocation]
    let technicalMessages: TechnicalMessages
    let serverVersion, dialectVersion, requestID: String
    
    enum CodingKeys: String, CodingKey {
        case stopLocationOrCoordLocation
        case technicalMessages = "TechnicalMessages"
        case serverVersion, dialectVersion
        case requestID = "requestId"
    }
}

// MARK: - StopLocationOrCoordLocation
struct StopLocationOrCoordLocation: Codable {
    let stopLocation: StopLocation
    
    enum CodingKeys: String, CodingKey {
        case stopLocation = "StopLocation"
    }
}

// MARK: - StopLocation
struct StopLocation: Identifiable, Codable {
    let locationNotes: LocationNotes
    let altID: [String]
    let timezoneOffset: Int
    let id, extID, name: String
    let lon, lat: Double
    let weight, products: Int
    
    enum CodingKeys: String, CodingKey {
        case locationNotes = "LocationNotes"
        case altID = "altId"
        case timezoneOffset, id
        case extID = "extId"
        case name, lon, lat, weight, products
    }
}

// MARK: - LocationNotes
struct LocationNotes: Codable {
    let locationNote: [LocationNote]
    
    enum CodingKeys: String, CodingKey {
        case locationNote = "LocationNote"
    }
}

// MARK: - LocationNote
struct LocationNote: Codable {
    let value, key, type, txtN: String
}

// MARK: - TechnicalMessages
struct TechnicalMessages: Codable {
    let technicalMessage: [TechnicalMessage]
    
    enum CodingKeys: String, CodingKey {
        case technicalMessage = "TechnicalMessage"
    }
}

// MARK: - TechnicalMessage
struct TechnicalMessage: Codable {
    let value, key: String
}
  • Related