如何在 Swift 中优雅地处理 JSON

因为Swift对于类型有非常严格的控制,它在处理JSON时是挺麻烦的,因为它天生就是隐式类型。SwiftyJSON是一个能帮助我们在Swift中使用JSON的开源类库。开始之前,让我们先看一下在Swift中处理JSON是多么痛苦。

在Swift中使用JSON的问题

以Twitter API为例。使用Swift,从tweet中取得一个用户的“name”值应该非常简单。下面就是我们要处理的JSON:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
[
   {
     ......
     "text" "just another test" ,
     ......
     "user" : {
       "name" "OAuth Dancer" ,
       "favourites_count" : 7,
       "entities" : {
         "url" : {
           "urls" : [
             {
               "expanded_url" null ,
               "url" "http://bit.ly/oauth-dancer" ,
               "indices" : [
                 0,
                 26
               ],
               "display_url" null
             }
           ]
         }
       ......
     },
     "in_reply_to_screen_name" null ,
   },
   ......]

在Swift中,你必须这样使用:

?
1
2
3
4
5
6
7
8
9
10
11
let jsonObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(dataFromTwitter, options: NSJSONReadingOptions.MutableContainers, error:  nil )
if  let statusesArray = jsonObject as? NSArray{
     if  let aStatus = statusesArray[ 0 ] as? NSDictionary{
         if  let user = aStatus[ "user" ] as? NSDictionary{
             if  let userName = user[ "name" ] as? NSDictionary{
                 //Finally We Got The Name
 
             }
         }
     }
}

或者,你可以用另外的一个方法,但这不易于阅读:

?
1
2
3
4
let jsonObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(dataFromTwitter, options: NSJSONReadingOptions.MutableContainers, error:  nil )
if  let userName = (((jsonObject as? NSArray)?[ 0 ] as? NSDictionary)?[ "user" ] as? NSDictionary)?[ "name" ]{
   //What  A  disaster above
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值