標籤:
訪問以下連結可以得到京城當天的天氣: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右邊會列印出如下訊息:
SWIFT解析天氣JSON格式