iOS入门学习(json解析)

1》首先获取数据,并把获取的json字符串转换为NSData类型

var url = NSURL(string: "http://www.weather.com.cn/data/cityinfo/101010100.html")
var data = NSData(contentsOfURL: url!)

2》然后将data转换为object类型

let json_b : AnyObject! = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

3》解析
let info : AnyObject! = json_b.objectForKey("retData")
self.city_name.text = info.objectForKey("city") as? String

在3步骤时,会提醒我们抛出异常

do{}catch{}

                do{
                    var url = NSURL(string: "http://www.weather.com.cn/data/cityinfo/101010100.html")
                    var data = NSData(contentsOfURL: url!)
                    let json_b : AnyObject! = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
                    let info : AnyObject! = json_b.objectForKey("retData")
                    self.city_name.text = info.objectForKey("city") as? String
                    self.weather.text = info.objectForKey("weather") as? String
                    self.temp.text = (info.objectForKey("temp") as? String)! + "°"
                    self.date.text = info.objectForKey("date") as? String
                    self.time.text = info.objectForKey("time") as? String
                    self.h_temp.text = (info.objectForKey("h_tmp") as? String)! + "°"
                    self.l_temp.text = (info.objectForKey("l_tmp") as? String)! + "°"
                    self.wd.text = info.objectForKey("WD") as? String
                    self.ws.text = info.objectForKey("WS") as? String
                    self.sunrise.text = info.objectForKey("sunrise") as? String
                    self.sunset.text = info.objectForKey("sunset") as? String
                    print(info)
                }catch{
                    print("no")
                }

完成

你可能感兴趣的:(ios,json,swift)