iOS开发——网络编程Swift篇&(八)SwiftyJSON详解

时间:2022-06-01 21:05:20

SwiftyJSON详解

最近看了一些网络请求的例子,发现Swift在解析JSON数据时特别别扭,总是要写一大堆的downcast(as?)和可选(Optional),看?号都看花了。随后发现了这个库SwiftyJSON,问题迎刃而解,灰常优雅和Swifty!

简单介绍下这个库(内容译自SwiftyJSONREADME):

为什么典型的在Swift中处理JSON的方法不好?

Swift语言是一种严格的类型安全语言,它要求我们显示的设置类型,并帮助我们写出更少bug的代码。但是当处理JSON这种天生就是隐式类型的数据结构,就非常麻烦了。

拿Twitter中timeline API返回的数据为例:

 [
   {
     ......
     "text": "just another test",
     ......
     "user": {
       "name": "OAuth Dancer",
       ,
       "entities": {
         "url": {
           "urls": [
             {
               "expanded_url": null,
               "url": "http://bit.ly/oauth-dancer",
               "indices": [
                 ,

               ],
               "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{
     ] 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)
 ] as? NSDictionary)?["user"] as? NSDictionary)?["name"]{
   //上面这一堆是个啥??
 }

使用SwiftyJSON

你只要这样做就行了:

let json = JSONValue(dataFromNetworking)
if let userName = json[0]["user"]["name"].string{
  //恩~ `name`到手,就这么简单
}

你不需要考虑可选类型的拆包和是否能拆包的判断,这些都自动完成了:

 let json = JSONValue(dataFromNetworking)
 ]["wrong_key"]["wrong_name"].string{
   //冷静,嘿嘿~ 调用不存在的["wrong_key]也不会crash滴, .string最终能安全的返回一个字符串或`nil`
 }

 let json = JSONValue(jsonObject)
 switch json["user_id"]{
 case .JString(let stringValue):
     let id = stringValue.toInt()
 case .JNumber(let doubleValue):
     let id = Int(doubleValue)
 default:
     println("ooops!!! JSON Data is Unexpected or Broken")

后记:SwiftyJSON是怎么做到的?

看到这个库之后,一方面很爽终于有合适的处理JSON的方法了;另一方面心里其实很好奇它是怎么做到的?

通过看源代码,才了解到它是创建了一个JSONValue枚举,这个枚举中有一个JInvalid类型。当使用json字符串来构造JSONValue对象时,如果无法构建成功,就会返回这个JInvalid枚举对象,然后对这个JInvalid枚举对象继续处理,会继续返回JInvalid。直到对其调用string, number, bool之类来获取Swift中的数据类型值时,才会返回nil

这套机制是类似于Optional<T>可选类型的,但是不同的是,Optional中对nil调用方法会crash,但JSONValue中对JInvalid调用方法不会crash,而是继续返回JInvalid。这样使用时就不用写一堆?号啦,反正不会出错滴。

同时,它给JSONValue枚举还创建了其它json中使用到的各种类型JNumber, JString, JBool,它们能通过构造器将原始值包装起来,然后最后通过对应的numberstringbool等属性方法来拆包,得到原始值。

推荐大家也读读这个库的源代码,其对enum的使用灰常巧妙!

json-swift 和 SwiftyJSON 的比较

最近微博上 @SwiftLanguage 让我对这两个库做个简单比较,所以就有了下文:

json-swiftSwiftyJSON都使用了一个自定义的枚举类型来描述JSON数据;通过重载实现了类似Array和Dictionary的下标操作;并可以将NSData类型的json实例转换成其对应的枚举类型的实例。

它们都解决了原来访问JSON类型数据时,必须手动downcast的繁琐操作,如原来要json[“blogs”]? as? Array,现在json[“blogs”]?即可。SwiftyJSON更进一步,连?也可以省掉,使用上更接近Objective-C风格;json-swift保留了?,跟Swift整体风格一致,此外还提供了直接从字面值实例化的便捷操作。

关于用不用?,我个人倾向于SwiftyJSON的做法。其最大优势是可以省写很多?号,无论写程序还是看程序都变得更简单直观;同时由于json结构中数据类型本身就是动态的,如果把每次取值当做一次操作,那么取值的过程不那么type-safe我认为可以接受,只要最终能保证取值结果跟Swift兼容(可选类型)。

if you love it, please page to :https://github.com/SwiftyJSON/SwiftyJSON

 Why is the typical JSON handling in Swift NOT good?

 Swift is very strict about types. But although explicit typing is good for saving us from mistakes, it becomes painful when dealing with JSON and other areas that are, by nature, implicit about types.

 Take the Twitter API for example. Say we want to retrieve a user's "name" value of some tweet in Swift (according to Twitter's API https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline).

 The code would look like this:

 let JSONObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil)

 if let statusesArray = JSONObject as? [AnyObject],
    let status = statusesArray[] as? [String: AnyObject],
    let user = status["user"] as? [String: AnyObject],
    let username = user["name"] as? String {
     // Finally we got the username
 }

 It's not good.

 Even if we use optional chaining, it would be messy:

 let JSONObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil)

 ] as? [String: AnyObject])?["user"] as? [String: AnyObject])?["name"] as? String {
     // What a disaster
 }

 An unreadable mess--for something that should really be simple!

 With SwiftyJSON all you have to do is:

 let json = JSON(data: dataFromNetworking)
 ]["user"]["name"].string{
   //Now you got your value
 }

 And don't worry about the Optional Wrapping thing. It's done for you automatically.

 let json = JSON(data: dataFromNetworking)
 ]["wrong_key"]["wrong_name"].string{
     //Calm down, take it easy, the ".string" property still produces the correct Optional String type with safety
 } else {
     //Print the error
     println(json[]["wrong_key"]["wrong_name"])
 }

 Requirements

     iOS 7.0+ / Mac OS X 10.9+
     Xcode 6.1

 Integration
 CocoaPods (iOS +, OS X 10.9+)

 You can use Cocoapods to install SwiftyJSONby adding it to your Podfile:

 platform :ios, '8.0'
 use_frameworks!

 target 'MyApp' do
     pod 'SwiftyJSON', '~> 2.2.0'
 end

 Note that it needs you to install CocoaPods  version, and requires your iOS deploy target >= 8.0:
 Carthage (iOS +, OS X 10.9+)

 You can use Carthage to install SwiftyJSON by adding it to your Cartfile:

 github 

 Manually (iOS +, OS X 10.9+)

 To use this library in your project manually you may:

     for Projects, just drag SwiftyJSON.swift to the project tree
     for Workspaces, include the whole SwiftyJSON.xcodeproj

 Usage
 Initialization

 import SwiftyJSON

 let json = JSON(data: dataFromNetworking)

 let json = JSON(jsonObject)

 if let dataFromString = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
     let json = JSON(data: dataFromString)
 }

 Subscript

 //Getting a double from a JSON Array
 let name = json[].double

 //Getting a string from a JSON Dictionary
 let name = json["name"].stringValue

 //Getting a string using a path to the element
 let path = [,,"name"]
 let name = json[path].string
 //Just the same
 let name = json[][]["name"].string
 //Alternatively
 let name = json[,,"name"].string

 //With a hard way
 let name = json[].string

 //With a custom way
 let keys:[SubscriptType] = [,,"name"]
 let name = json[keys].string

 Loop

 //If json is .Dictionary
 for (key: String, subJson: JSON) in json {
    //Do something you want
 }

 The first element is always a String, even if the JSON is an Array

 //If json is .Array
 //The `index` is 0..<json.count's string value
 for (index: String, subJson: JSON) in json {
     //Do something you want
 }

 Error

 Use a subscript to get/set a value in an Array or Dictionary

 If the json is:

     an array, the app may crash with "index out-of-bounds."
     a dictionary, it will get nil without a reason.
     not an array or a dictionary, the app may crash with an "unrecognised selector" exception.

 It will never happen in SwiftyJSON.

 let json = JSON(["name", "age"])
 ].string {
     //Do something you want
 } else {
     println(json[].error) // "Array[999] is out of bounds"
 }

 let json = JSON([])
 if let name = json["address"].string {
     //Do something you want
 } else {
     println(json["address"].error) // "Dictionary["address"] does not exist"
 }

 let json = JSON()
 ].string {
     //Do something you want
 } else {
     println(json[])       // "Array[0] failure, It is not an array"
     println(json[].error) // "Array[0] failure, It is not an array"
 }

 if let name = json["name"].string {
     //Do something you want
 } else {
     println(json["name"])       // "Dictionary[\"name"] failure, It is not an dictionary"
     println(json["name"].error) // "Dictionary[\"name"] failure, It is not an dictionary"
 }

 Optional getter

 //NSNumber
 if let id = json["user"]["favourites_count"].number {
    //Do something you want
 } else {
    //Print the error
    println(json["user"]["favourites_count"].error)
 }

 //String
 if let id = json["user"]["name"].string {
    //Do something you want
 } else {
    //Print the error
    println(json["user"]["name"])
 }

 //Bool
 if let id = json["user"]["is_translator"].bool {
    //Do something you want
 } else {
    //Print the error
    println(json["user"]["is_translator"])
 }

 //Int
 if let id = json["user"]["id"].int {
    //Do something you want
 } else {
    //Print the error
    println(json["user"]["id"])
 }
 ...

 Non-optional getter

 Non-optional getter is named xxxValue

 //If not a Number or nil, return 0
 let id: Int = json["id"].intValue

 //If not a String or nil, return ""
 let name: String = json["name"].stringValue

 //If not a Array or nil, return []
 let list: Array<JSON> = json["list"].arrayValue

 //If not a Dictionary or nil, return [:]
 let user: Dictionary<String, JSON> = json["user"].dictionaryValue

 Setter

 json["name"] = JSON("new-name")
 json[] = JSON()

 json[
 json["coordinate"].double =  8766.766
 json["name"].string =  "Jack"
 json.arrayObject = [,,,]
 json.dictionary = []

 Raw object

 let jsonObject: AnyObject = json.object

 if let jsonObject: AnyObject = json.rawValue

 //convert the JSON to raw NSData
 if let data = json.rawData() {
     //Do something you want
 }

 //convert the JSON to a raw String
 if let string = json.rawString() {
     //Do something you want
 }

 Literal convertibles

 For more info about literal convertibles: Swift Literal Convertibles

 //StringLiteralConvertible
 let json: JSON = "I'm a json"

 //IntegerLiteralConvertible
 let json: JSON =  

 //BooleanLiteralConvertible
 let json: JSON =  true

 //FloatLiteralConvertible
 let json: JSON =  2.8765

 //DictionaryLiteralConvertible
 let json: JSON =  ["I":"am", "a":"json"]

 //ArrayLiteralConvertible
 let json: JSON =  ["I", "am", "a", "json"]

 //NilLiteralConvertible
 let json: JSON =  nil

 //With subscript in array
 var json: JSON =  [,,]
 json[] =
 json[] =
 json[] =
 json[] =  //Don't worry, nothing will happen

 //With subscript in dictionary
 var json: JSON =  []
 json["name"] = "Mike"
 json[" //It's OK to set String
 json["address"] = "L.A." // Add the "address": "L.A." in json

 //Array & Dictionary
 var json: JSON =  [, "list": ["a", "b", "c", ["what": "this"]]]
 json[]["what"] = "that"
 json[,"what"] = "that"
 let path = [,"what"]
 json[path] = "that"

 Work with Alamofire

 SwiftyJSON nicely wraps the result of the Alamofire JSON response handler:

 Alamofire.request(.GET, url, parameters: parameters)
   .responseJSON { (req, res, json, error) in
     if(error != nil) {
       NSLog("Error: \(error)")
       println(req)
       println(res)
     }
     else {
       NSLog("Success: \(url)")
       var json = JSON(json!)
     }
   }