2014-10-05 22 views
0

我在寫一個Swift項目來從天氣API Wunderground獲取天氣數據。現在我可以提取諸如溫度或相對溼度等信息,但是我很難用swift獲取存儲在嵌套列表內部列表中的信息。例如,我無法獲取存儲在「current_observation」中的「display_location.state」的信息。如何在天氣中查找以json數據格式存儲的特定信息API

這裏是由Wunderground提供的天氣信息的一個例子:

{ 
    "response": { 
    "version":"0.1", 
    "termsofService":"http://www.wunderground.com/weather/api/d/terms.html", 
    "features": { 
    "conditions": 1 
    } 
    } 
    , "current_observation": { 
     "image": { 
     "url":"http://icons.wxug.com/graphics/wu2/logo_130x80.png", 
     "title":"Weather Underground", 
     "link":"http://www.wunderground.com" 
     }, 
     "display_location": { 
     "full":"San Francisco, CA", 
     "city":"San Francisco", 
     "state":"CA", 
     "state_name":"California", 
     "country":"US", 
     "country_iso3166":"US", 
     "zip":"94101", 
     "magic":"1", 
     "wmo":"99999", 
     "latitude":"37.77500916", 
     "longitude":"-122.41825867", 
     "elevation":"47.00000000" 
     }, 
     "temperature_string":"76.3 F (24.6 C)", 
     "relative_humidity":"43%", 
    } 
} 

這是我在提取氣象信息斯威夫特代碼:

var url = NSURL(string:"http://api.wunderground.com/api/56968011acc3e3eb/conditions/q/\(state)/\(city).json") 
var data = NSData.dataWithContentsOfURL(url, options: NSDataReadingOptions.DataReadingUncached, error: nil) 
var str = NSString(data:data, encoding:NSUTF8StringEncoding) 
var json:AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil) 
var weatherInfo:AnyObject! = json.objectForKey("current_observation") 
var currentTemp: AnyObject! = weatherInfo.objectForKey("temperature_string") 
var humidity:AnyObject! = weatherInfo.objectForKey("relative_humidity") 
var wind:AnyObject! = weatherInfo.objectForKey("wind_kph") 
display.text = "Temperature: \(currentTemp)\nHumidity: \(humidity)\nWind: \(wind)\n" 

謝謝!

回答

1

有關樣式的快速註釋,任何時候在第一次設置變量後都不會更改變量的值時,應該使用let而不是var

唯一看起來不正確的是如何將子對象拉出JSON。請記住,在JSON數據結構是這樣的

NSDictionary { 
    "response": NSDictionary {}, 
    "current_observation": NSDictionary { 
      "relative_humidity": NSString 
      ... 
    } 
    ... 
} 

所以,當你拉的對象,如current_observation了,你需要確保你投的東西到合適的對象

let json = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.AllowFragments, error:nil) as NSDictionary 
let weatherInfo = json["current_observation"] as NSDictionary 
let currentTemp = weatherInfo["temperature_string"] as NSString 
... 

儘管完全誠實,但對於這樣的事情,我會推薦使用EasyMapping。然後,你可以設置快捷類來表示JSON和地圖提供商所以你可以做這樣的事情

if let weatherInfo = EKMapper.objectFromExternalRepresentation(json, withMapping:/*mapping provider*/) { 
    //do stuff 
} 

,然後你擁有這一切從JSON反序列化進入迅捷的對象。這也可以防止應用程序崩潰,如果JSON結構更改或缺少您期望在那裏的值。