在Swift中優雅地處理JSON

來源:互聯網
上載者:User

在Swift中優雅地處理JSON

SwiftyJSON的使用十分的簡單:

典型的NSURLSessionTask抓取Twitter的API將產生dataFromNetwork: NSData!:

你首先應該做的事情是初始化JSONValue:

  1. let json = JSONValue(dataFromNetwork) 

JSONValue是一個枚舉類型表示一個典型的JSON資料結構。

你能使用subscripts檢索不同的值從原始的JSONValue中,像這樣:

  1. let userName:JSONValue = json[0]["user"]["name"] 

注意userName仍然是一個JSONValue。那怎樣得到一個字串呢?

你能用.string屬性得到JSON資料表示的真正值。

  1. let userNameString = userName.string! 

對每一種JSON類型, JSONValue都提供了一種屬性檢索它:

  1. var string: String? 
  2. var number: NSNumber? 
  3. var bool: Bool?  
  4. var array: Array<JSONValue>? 
  5. var object: Dictionary<String, JSONValue>? 

注意每一種屬性都是一個Optional值。這是因為JSON資料能包含任何它定義的有效類型。

因此,建議的方式是用Optional綁定檢索值:

  1. if let name = userName.string{ 
  2.     //This could avoid lots of crashes caused by the unexpected data types 
  3. } 
  4.   
  5. if let name = userName.number{ 
  6.     //As the value of the userName is Not a number. It won't execute. 

.number屬性產生一個NSNumber值,在Swift中這通常不是很有用。你能用.double或者.integer得到一個Double值或者一個Int值。

  1. if let intValue = numberValue.integer{ 
  2.     count += intValue 
  3. } 
枚舉Enumeration)

在Swift中JSONValue實際上是一個枚舉:

  1. enum JSONValue { 
  2.   
  3.     case JNumber(NSNumber) 
  4.     case JString(String) 
  5.     case JBool(Bool) 
  6.     case JNull 
  7.     case JArray(Array<JSONValue>) 
  8.     case JObject(Dictionary<String,JSONValue>) 
  9.     case JInvalid(NSError) 
  10.   
  11. } 

你可以使用一個switch子句去更有效地擷取值:

  1. let json = JSONValue(jsonObject) 
  2. switch json["user_id"]{ 
  3. case .JString(let stringValue): 
  4.     let id = stringValue.toInt() 
  5. case .JNumber(let numberValue): 
  6.     let id = numberValue.integerValue 
  7. default: 
  8.     println("ooops!!! JSON Data is Unexpected or Broken") 
下標Subscripts)

注意,在JSON中一個數組結構被封裝成intoArray<JSONVlaue>,它意味著數組裡的每一個元素都是一個JSONValue。甚至你從JSONValue中取出一個數組,你仍然可以使用基本的屬性去擷取元素的值:

  1. if let array = json["key_of_array"].array{ 
  2.     if let string = array[0].string{ 
  3.         //The array[0] is still a JSONValue! 
  4.     } 
  5. } 

對象也是一樣。因此,推薦的方式是訪問每一個數組和對象時使用JSONValue的下標。

  1. if let string = json["key_of_array"][0].string{ 
  2.   
  3. } 

實際上,你可以用下標訪問一個JSONValue,還不用擔心執行階段錯誤導致的崩潰:

  1. let userName = json[99999]["wrong_key"] 

如果你使用推薦的方式去取資料,它是安全的:

  1. if let userName = json[99999]["wrong_key"]["name"].string{ 
  2.     //It's always safe 
  3. } 
列印

JSONValue遵守Printable協議.所以很容易在原始字串中得到JSON資料:

  1. let json = JSONValue(dataFromNetwork) 
  2. println(json) 
  3. /*You can get a well printed human readable raw JSON string: 
  4.       { 
  5.         "url": { 
  6.           "urls": [ 
  7.             { 
  8.               "expanded_url": null, 
  9.               "url": "http://bit.ly/oauth-dancer", 
  10.               "indices": [ 
  11.                 0, 
  12.                 26 
  13.               ], 
  14.               "display_url": null 
  15.             } 
  16.           ] 
  17.        } 
  18. */ 

如果你不想列印出來,你可以使用.description屬性來得到上述字串。

  1. let printableString = json.description 
調試與錯誤處理

要是JSON資料出錯或者我們錯誤地檢索資料,那會怎麼樣呢?你可以使用if語句來測試:

  1. let json = JSONValue(dataFromNetworking)["some_key"]["some_wrong_key"]["wrong_name"] 
  2. if json{ 
  3.   //JSONValue it self conforms to Protocol "LogicValue", with JSONValue.JInvalid stands for false and others stands true 
  4. } 

如果我們嘗試使用錯誤的索引值或索引來訪問資料,description屬性會高數你KeyPath在哪裡出錯了.

  1. let json = JSONValue(dataFromNetworking)["some_key"]["some_wrong_key"]["wrong_name"] 
  2. if json{ 
  3.   
  4. } else { 
  5.   println(json) 
  6.   //> JSON Keypath Error: Incorrect Keypath "some_wrong_key/wrong_name" 
  7.   //It always tells you where your key went wrong 
  8.   switch json{ 
  9.   case .JInvalid(let error): 
  10.     //An NSError containing detailed error information  
  11.   } 
  12. } 
後記

SwiftyJSON的開發將會發布在Github, 請持續關注後續版本。

本文連結:http://mobile.51cto.com/design-446157.htm

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.