Разбор JSON Словарь Swift5 - PullRequest
       7

Разбор JSON Словарь Swift5

0 голосов
/ 10 апреля 2020

Я пытаюсь проанализировать данные из OpenWeatherMap API в Swift 5, но я не уверен, почему он возвращает ноль для двух значений описания и значка, который находится под погодой. Я могу получить значение для даты и могу напечатать весь объект JSON в моей консоли. Кто-нибудь может помочь?

"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
        }
    }
}

А потом на моем 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)
            }
        }

    }

1 Ответ

1 голос
/ 10 апреля 2020

Причина - ваша погода - это не словарь. Это массив. Так что вам нужно получить как массив, а затем словарь.

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
        }
...