解析 JSON 字典 Swift5
Posted
技术标签:
【中文标题】解析 JSON 字典 Swift5【英文标题】:Parsing JSON Dictionary Swift5 【发布时间】:2020-04-10 07:23:49 【问题描述】:我正在尝试在 Swift 5 中解析来自 OpenWeatherMap API 的数据,但我不确定为什么它会为两个处于天气状态的描述和图标值返回 null。我可以接收日期值并可以在我的控制台中打印整个 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
然后在我的视图控制器上:
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】:原因是你的 weather 不是字典。它是一个数组。所以你需要先获取数组然后字典。
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
【讨论】:
@Sanaz 如果它正在工作,请将答案标记为已接受。它将帮助与您在这里遇到相同问题的未来读者。以上是关于解析 JSON 字典 Swift5的主要内容,如果未能解决你的问题,请参考以下文章