SwiftyJSON库
为什么典型的在Swift中处理JSON的方法不好?Swift语言是一种严格的类型安全语言,它要求我们显示的设置类型,并帮助我们写出更少bug的代码。但是当处理JSON这种天生就是隐式类型的数据结构,就非常麻烦了。
拿Twitter中timeline API返回的数据为例:
[
{
......
"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中的解析代码会是这样:
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{
//终于我们得到了name
}
}
}}
不好吧。就算是换成可选链式调用,也还是一团糟:
let jsonObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(dataFromTwitter, options: NSJSONReadingOptions.MutableContainers, error: nil)if let userName = (((jsonObject as? NSArray)?[0] as? NSDictionary)?["user"] as? NSDictionary)?["name"]{
//上面这一堆是个啥??
}
使用SwiftyJSON你只要这样做就行了:
let json = JSONValue(dataFromNetworking)if let userName = json[0]["user"]["name"].string{
//恩~ name
到手,就这么简单
}
```