Swift2.0中Json数据的解析教程

(转载自:http://blog.csdn.net/ios_of_swift/article/details/47280483)


1.在swift1.0时代,解析的前几句可能是这样的

[plain]  view plain copy
  1. <span style="white-space:pre">    </span>let url = NSURL(string: "Server")  
  2.         let data = NSData(contentsOfURL: url)  
  3.         let object = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers,error:nil)  
或者是这样的

[plain]  view plain copy
  1. <span style="white-space:pre">    </span>var url = NSURL(string:"Server")  
  2. <span style="white-space:pre">    </span>var data = NSData.dataWithContentsOfURL(url,options:NSDataReadingOptions.DataReadingUncached,error:nil)  
  3. <span style="white-space:pre">    </span>var json:AnyObject = NSJSONSerialization.JSONObjectWithData(data,options:NSJSONReadingOptions.AllowFragments,error:nil)  
但是一旦你用在Swift2.0里面就......Extra argument ’error‘ in call了

然后我就必应了一下

发现Swift2.0的拋错误的正确姿势是这样的

[plain]  view plain copy
  1. do  {  
  2.         let object = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)  
  3.         }  
  4.         catch {  
  5.             print(error)  
  6.         }  

顿时hehe了

所以说应该这样写喽

[plain]  view plain copy
  1. <span style="white-space:pre">    </span>let url = NSURL(string: "Server")  
  2.         let data = NSData(contentsOfURL: url!)  
  3.         do  {  
  4.         let object = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)  
  5.         }  
  6.         catch {  
  7.             print(error)  
  8.         }  

原来如此,这里Swift2.0的抛错误方式再也不是error:nil了

而是do{

try ...

}

catch{

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值