首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >解析JSON字典Swift5

解析JSON字典Swift5
EN

Stack Overflow用户
提问于 2020-04-10 07:23:49
回答 1查看 98关注 0票数 1

我正在尝试解析Swift 5中的OpenWeatherMap API中的数据,但我不知道为什么它会返回null作为描述和图标的两个值,这两个值都是在天气下的。我可以接收日期的值,并可以在我的控制台中打印整个JSON对象。有人能帮忙吗?

代码语言:javascript
复制
"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"
}, 
代码语言:javascript
复制
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
        }
    }
}

然后在我的视图控制器上:

代码语言:javascript
复制
    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)
            }
        }

    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-10 07:41:25

原因是你的天气,不是一个Dictionary.It,是一个array.So,你需要得到它的数组,然后是字典。

代码语言:javascript
复制
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
        }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61135709

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档