SALE: Save 50% on all my books and bundles >>

JSON not decoding

Forums > SwiftUI

I have trying to get some info from a website and using the following code. I get the data back but it does not decode

struct ResultsView: View {
    @State private var results = [Result]()

    var busId: String = "386"

     let appId = "" // giving app_id
    let appKey = "" // giving app_key

    var body: some View {
        List(results, id: \.lastUpdate) { item in
            VStack(alignment: .leading) {
        .onAppear(perform: loadData)


    func loadData() {
        guard let url = URL(string: "\(busId)/Disruption?app_id=\(appId)&app_key=\(appKey)") else {
            print("Invalid URL")

        let request = URLRequest(url: url)

        URLSession.shared.dataTask(with: request) { data, response, error in
            if let data = data {
                if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
                    DispatchQueue.main.async {
                        self.results = decodedResponse.results
            print("Fetch failed: \(error?.localizedDescription ?? "Unknown Error")")

Have these structs

struct Response: Codable {
    var results: [Result]

struct Result: Codable {
    var lastUpdate: String
    var description: String

Any idea what I have done wrong?


It might help if you could post your JSON response so we can see if you have set up your Codable structs properly


Please bear in mind that this is a link to live site and could change

this is what the response looks

[{"$type":"Tfl.Api.Presentation.Entities.Disruption, Tfl.Api.Presentation.Entities","category":"RealTime","type":"lineInfo","categoryDescription":"RealTime","description":"CHANGES TO ROUTE 246: Until further notice, the route will not operate between Westerham and Chartwell due to the closure of Chartwell House. All journeys will operate between Bromley North and Westerham only.","created":"2020-03-23T09:30:00Z","lastUpdate":"2020-03-23T09:32:00Z","affectedRoutes":[],"affectedStops":[]}]

or visit TfL with complete brakdown!/Line/Line_Disruption


@StewartLynch Did that help?


Hacking with Swift is sponsored by RevenueCat

SPONSORED Building in-app subscriptions are hard. RevenueCat makes it simple. With their open source SDKs, you can painlessly implement subscriptions for your app in hours, not months.

Explore the docs to learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Cascable unleashes the power of your camera and unlocks powerful workflows for shooting, managing, and geotagging your photos.

Unknown user

Not logged in

Log in