我有一些我正在从Wunderground下载的天气数据,当我访问网站时,信息会正确地返回,但是当我解析此信息时,我所拥有的标签应该更改。这是代码......
let jsonResult: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
if let city = jsonResult["current_observation"] as? NSDictionary {
if let weatherInfo = city["estimated"] as? NSDictionary{
if let currentTemp = weatherInfo["feelslike_string"] as? NSString {
self.temperatureLabel.text = currentTemp
}
}
}
这是JSON(部分内容):
{
"current_observation" = {
UV = 0;
"dewpoint_c" = 16;
"dewpoint_f" = 60;
"dewpoint_string" = "60 F (16 C)";
"display_location" = {
city = "San Francisco";
country = US;
"country_iso3166" = US;
elevation = "47.00000000";
full = "San Francisco, CA";
latitude = "37.77500916";
longitude = "-122.41825867";
magic = 1;
state = CA;
"state_name" = California;
wmo = 99999;
zip = 94101;
};
estimated = {
};
"feelslike_c" = "16.4";
"feelslike_f" = "61.5";
"feelslike_string" = "61.5 F (16.4 C)";
"forecast_url" = "http://www.wunderground.com/US/CA/San_Francisco.html";
"heat_index_c" = NA;
"heat_index_f" = NA;
"heat_index_string" = NA;
"history_url" = "http://www.wunderground.com/weatherstation/WXDailyHistory.asp?ID=KCASANFR49";
icon = cloudy;
任何帮助将不胜感激!谢谢
答案 0 :(得分:0)
您的JSON
看起来格格不入。 estimated
将是一个空字典,所以这一行:
if let currentTemp = weatherInfo["feelslike_string"] as? NSString
不会返回true
,因为weatherInfo
没有密钥"feelslike_string"
的对象 - 它会返回nil
。
"feelslike_string"
是"current_observation"
字典的成员,而不是"estimated"
字典的成员。此JSON中的"estimated"
字典为空,并且没有键"feelslike_string"
的值。
所以我们需要将代码更改为:
if let currentObs = jsonResult["current_observation"] as? NSDictionary {
if let currentTemp = currentObs["feelslike_string"] as? NSString {
self.temperatureLabel.text = currentTemp
}
}