Swift & JSON

Aus Wikizone
Wechseln zu: Navigation, Suche

Links[Bearbeiten]

Swift - Snippets
Swift (Programmiersprache)
Swift - Möglichkeiten Daten zu speichern#Speichern von JSON Daten mit File I/O
Swift JSONEncoder

Beispiel[Bearbeiten]

func parseJSON(weatherData: Data) {
        let decoder = JSONDecoder()
        // decode needs a type not an object as parameter. We refer to the type with .self i.e. WeatherData.self
        do {
            let decodedData = try decoder.decode(WeatherData.self, from: weatherData)
            let id = decodedData.weather[0].id
            let temp = decodedData.main.temp
            let name = decodedData.name
            
            let weather = WeatherModel(conditionId: id, cityName: name, temperature: temp)
            print( "weatherName (sf-symbol): \(weather.conditionName)")
            print( "temperature: \(weather.temperatureStr)")
            
        } catch {
            print("Error parsing JSON: \(error)")
        }
    }