您的位置:首页 > 移动开发 > Swift

SWIFT解析天气JSON格式

2015-05-03 21:21 197 查看
访问以下链接可以得到京城当天的天气:http://www.weather.com.cn/adat/sk/101010100.html

返回的JSON格式如下:

{"weatherinfo":{"city":"北京","cityid":"101010100","temp":"9","WD":"西南风","WS":"2级","SD":"22%","WSE":"2","time":"10:35","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB","njd":"暂无实况","qy":"1015"}}

好吧,接下来我就建立一个playground并敲入以下代码,暂无把所有的错误设为nil:

var url = NSURL(string: "http://www.weather.com.cn/adat/sk/101010100.html")

var data = NSData(contentsOfURL: url!, options: NSDataReadingOptions.DataReadingUncached, error: nil)

var json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments, error: nil)

//解析JSON数据

var weatherinfo:AnyObject? = json?.objectForKey("weatherinfo")

var cityId:NSString = weatherinfo?.objectForKey("cityid") as NSString

var city:NSString = weatherinfo?.objectForKey("city") as NSString

var wind:NSString = weatherinfo?.objectForKey("WD") as NSString

playground右边会打印出如下消息:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: