Search code examples
jsonswiftalamofire

Parsing JSON Dictionary Swift5


I am trying to parse data from OpenWeatherMap API in Swift 5 but I am not sure why it is returning null for two values of description and icon which is under weather. I can receive value for date and can print the whole JSON object in my console. Can anyone help?

"list": [
{
"dt": 1485799200,
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "02n"
}
],
"wind": {
"speed": 4.77,
"deg": 232.505
},
"dt_txt": "2017-01-30 18:00:00"
}, 
class WeatherForecast {
    var _description : String?
    var _icon : String?
    var _date: String?
    init(weatherDict: Dictionary<String, Any>){
        if let weather = weatherDict["weather"] as? Dictionary<String, Any>{
            if let desc = weather["description"] as? String{
                        self._description = desc
                    }
                    if let icon = weather["icon"] as? String{
                        self._icon = icon
                    }
                }
                if let rdate = weatherDict["dt_txt"] as? String{
                    self._date = rdate
        }
    }
}

And then on my viewcontroller:

    func getWeatherData(cityName: String){

        let url = URL(string: "http://api.openweathermap.org/data/2.5/forecast?q=\(cityName)&appid=**********")!
        AF.request(url).responseJSON{(response) in
            let result = response.result
            switch result {
            case.success(let value): print(value)
                if let dictionary = value as? Dictionary<String, AnyObject>{
                                if let list = dictionary["list"] as? [Dictionary<String, AnyObject>]{
                                    for item in list{
                                        let forcast = WeatherForecast(weatherDict: item)
                                        self.weatherForcasts.append(forcast)
                                    }
                                    print(self.weatherForcasts.count)
                                    self.weatherTableView.reloadData()
                                }
                            }
            case.failure(let error): print(error)
            }
        }

    }

Solution

  • Reason is your weather is not an Dictionary.It is an array.So you need to get as it array and then dictionary.

    if let weather = (weatherDict["weather"] as? Array ?? [])[0] as? Dictionary<String, Any>{
                if let desc = weather["description"] as? String{
                            self._description = desc
                        }
                        if let icon = weather["icon"] as? String{
                            self._icon = icon
                        }
                    }
                    if let rdate = weatherDict["dt_txt"] as? String{
                        self._date = rdate
            }