UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: How do I decode this JSON?

Forums > Swift

I'm trying to decode the JSON feed of this site: https://gbfs.urbansharing.com/edinburghcyclehire.com/station_information.json

I've created structs for the JSON feed like this:

import Foundation

// MARK: - Welcome
struct Welcome: Codable {
    var lastUpdated, ttl: Int
    var data: DataClass
}

// MARK: - DataClass
struct DataClass: Codable {
    var stations: [Station]
}

// MARK: - Station
struct Station: Codable {
    var stationID, name, address: String
    var lat, lon: Double
    var capacity: Int
}

and a ContentView like this:


import SwiftUI

struct ContentView: View {

    @State private var stations = [Station]()

    var body: some View {
        NavigationView {
            List(stations, id: \.name) { station in
                VStack(alignment: .leading) {
                    Text(station.name)
                        .font(.title2)
                    Text(String(station.capacity))
                }
            }
                .navigationBarTitle("Bike Docker", displayMode: .large)
            .onAppear(perform: loadStationData)
        }
    }

    func loadStationData() {
        guard let url = URL(string: "https://gbfs.urbansharing.com/edinburghcyclehire.com/station_information.json") else {
            print("Invalid URL")
            return
        }

        let request = URLRequest(url: url)

        URLSession.shared.dataTask(with: request) { data, response, error in
            if let data = data {
                print(data)
                if let decodedResponse = try?
                    JSONDecoder().decode(Welcome.self, from: data) {
                    DispatchQueue.main.async {
                     let welcome = decodedResponse
                        self.stations = welcome.data.stations
                    }
                    return
                }
            }
            print("Fetch failed: \(error?.localizedDescription ?? "Unknown error.")")
        }.resume()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

This always triggers the fatal error and never decodes = not sure what I am doing wrong.. would be immensely greatful for any help

3      

You variable names in the structs must exactly match the names in the JSON. There is no stationID and there is no lastUpdated. station_id and last_updated is the way to go or you choose a decoding strategy.

3      

If you want to make it easy to visualize the json you get you should try a safari extension. Either JSON peep or Simply JSON are pretty good. I prefer the 2nd, and both are free.

This will help you with identifying the details mentioned in the comment above. "Your properties need to be named exactly as they are in the JSON"

4      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.