访问以下链接可以得到京城当天的天气: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右边会打印出如下消息: