如何在weather API中查找以json数据格式存储的特定信息

时间:2014-10-05 02:55:29

标签: json swift weather-api

我正在编写一个Swift项目来获取天气API,Wunderground的天气数据。现在我可以提取温度或相对湿度等信息,但是我在使用swift获取存储在嵌套列表内部列表中的信息时遇到了麻烦。例如,我无法获取存储在“current_observation”中的“display_location.state”信息。

以下是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%",
    }
}

这是我提取天气信息的Swift代码:

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 个答案:

答案 0 :(得分: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。然后你可以设置swift类来表示JSON,并设置一个地图提供者,这样你就可以做类似

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

然后你将它从JSON反序列化为swift对象。如果JSON结构发生更改或缺少您希望存在的值,这也可以防止应用程序崩溃。