在Swift中優雅地處理JSON
SwiftyJSON的使用十分的簡單:
典型的NSURLSessionTask抓取Twitter的API將產生dataFromNetwork: NSData!:
你首先應該做的事情是初始化JSONValue:
- let json = JSONValue(dataFromNetwork)
JSONValue是一個枚舉類型表示一個典型的JSON資料結構。
你能使用subscripts檢索不同的值從原始的JSONValue中,像這樣:
- let userName:JSONValue = json[0]["user"]["name"]
注意userName仍然是一個JSONValue。那怎樣得到一個字串呢?
你能用.string屬性得到JSON資料表示的真正值。
- let userNameString = userName.string!
對每一種JSON類型, JSONValue都提供了一種屬性檢索它:
- var string: String?
- var number: NSNumber?
- var bool: Bool?
- var array: Array<JSONValue>?
- var object: Dictionary<String, JSONValue>?
注意每一種屬性都是一個Optional值。這是因為JSON資料能包含任何它定義的有效類型。
因此,建議的方式是用Optional綁定檢索值:
- if let name = userName.string{
- //This could avoid lots of crashes caused by the unexpected data types
- }
-
- if let name = userName.number{
- //As the value of the userName is Not a number. It won't execute.
.number屬性產生一個NSNumber值,在Swift中這通常不是很有用。你能用.double或者.integer得到一個Double值或者一個Int值。
- if let intValue = numberValue.integer{
- count += intValue
- }
枚舉Enumeration)
在Swift中JSONValue實際上是一個枚舉:
- enum JSONValue {
-
- case JNumber(NSNumber)
- case JString(String)
- case JBool(Bool)
- case JNull
- case JArray(Array<JSONValue>)
- case JObject(Dictionary<String,JSONValue>)
- case JInvalid(NSError)
-
- }
你可以使用一個switch子句去更有效地擷取值:
- let json = JSONValue(jsonObject)
- switch json["user_id"]{
- case .JString(let stringValue):
- let id = stringValue.toInt()
- case .JNumber(let numberValue):
- let id = numberValue.integerValue
- default:
- println("ooops!!! JSON Data is Unexpected or Broken")
下標Subscripts)
注意,在JSON中一個數組結構被封裝成intoArray<JSONVlaue>,它意味著數組裡的每一個元素都是一個JSONValue。甚至你從JSONValue中取出一個數組,你仍然可以使用基本的屬性去擷取元素的值:
- if let array = json["key_of_array"].array{
- if let string = array[0].string{
- //The array[0] is still a JSONValue!
- }
- }
對象也是一樣。因此,推薦的方式是訪問每一個數組和對象時使用JSONValue的下標。
- if let string = json["key_of_array"][0].string{
-
- }
實際上,你可以用下標訪問一個JSONValue,還不用擔心執行階段錯誤導致的崩潰:
- let userName = json[99999]["wrong_key"]
如果你使用推薦的方式去取資料,它是安全的:
- if let userName = json[99999]["wrong_key"]["name"].string{
- //It's always safe
- }
列印
JSONValue遵守Printable協議.所以很容易在原始字串中得到JSON資料:
- let json = JSONValue(dataFromNetwork)
- println(json)
- /*You can get a well printed human readable raw JSON string:
- {
- "url": {
- "urls": [
- {
- "expanded_url": null,
- "url": "http://bit.ly/oauth-dancer",
- "indices": [
- 0,
- 26
- ],
- "display_url": null
- }
- ]
- }
- */
如果你不想列印出來,你可以使用.description屬性來得到上述字串。
- let printableString = json.description
調試與錯誤處理
要是JSON資料出錯或者我們錯誤地檢索資料,那會怎麼樣呢?你可以使用if語句來測試:
- let json = JSONValue(dataFromNetworking)["some_key"]["some_wrong_key"]["wrong_name"]
- if json{
- //JSONValue it self conforms to Protocol "LogicValue", with JSONValue.JInvalid stands for false and others stands true
- }
如果我們嘗試使用錯誤的索引值或索引來訪問資料,description屬性會高數你KeyPath在哪裡出錯了.
- let json = JSONValue(dataFromNetworking)["some_key"]["some_wrong_key"]["wrong_name"]
- if json{
-
- } else {
- println(json)
- //> JSON Keypath Error: Incorrect Keypath "some_wrong_key/wrong_name"
- //It always tells you where your key went wrong
- switch json{
- case .JInvalid(let error):
- //An NSError containing detailed error information
- }
- }
後記
SwiftyJSON的開發將會發布在Github, 請持續關注後續版本。
本文連結:http://mobile.51cto.com/design-446157.htm