因为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
}
|