自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

在Swift中優(yōu)雅地處理JSON

移動開發(fā) Android
因為Swift對于類型有非常嚴格的控制,它在處理JSON時是挺麻煩的,因為它天生就是隱式類型。SwiftyJSON是一個能幫助我們在Swift中使用JSON的開源類庫。開始之前,讓我們先看一下在Swift中處理JSON是多么痛苦。

SwiftyJSON的使用十分的簡單:

典型的NSURLSessionTask抓取Twitter的API將產(chǎn)生dataFromNetwork: NSData!:

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

  1. let json = JSONValue(dataFromNetwork) 

JSONValue是一個枚舉類型表示一個典型的JSON數(shù)據(jù)結(jié)構(gòu)。

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

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

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

你能用.string屬性得到JSON數(shù)據(jù)表示的真正值。

  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數(shù)據(jù)能包含任何它定義的有效類型。

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

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

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

  1. if let intValue = numberValue.integer{ 
  2.     count += intValue 

枚舉(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.   

你可以使用一個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中一個數(shù)組結(jié)構(gòu)被包裝成intoArray<JSONVlaue>,它意味著數(shù)組里的每一個元素都是一個JSONValue。甚至你從JSONValue中取出一個數(shù)組,你仍然可以使用基本的屬性去獲取元素的值:

  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.     } 

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

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

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

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

如果你使用推薦的方式去取數(shù)據(jù),它是安全的:

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

打印

JSONValue遵守Printable協(xié)議.所以很容易在原始字符串中得到JSON數(shù)據(jù):

  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 

調(diào)試與錯誤處理

要是JSON數(shù)據(jù)出錯或者我們錯誤地檢索數(shù)據(jù),那會怎么樣呢?你可以使用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 

如果我們嘗試使用錯誤的鍵值或索引來訪問數(shù)據(jù),description屬性會高數(shù)你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.   } 

后記

 SwiftyJSON的開發(fā)將會發(fā)布在Github, 請持續(xù)關注后續(xù)版本。

本文鏈接:http://mobile.51cto.com/design-446157.htm

責任編輯:chenqingxiang 來源: oschina
相關推薦

2025-01-20 07:10:00

LambdaJavanull

2024-05-21 08:14:59

代碼接口依賴注入

2023-05-12 12:09:38

職責鏈模式客服

2024-09-26 10:51:51

2024-01-15 08:09:44

Fluent錯誤代碼

2024-10-14 11:08:53

程序異常延遲

2023-08-29 07:35:15

2025-02-07 09:11:04

JSON對象策略

2022-08-03 08:41:30

客戶端操作并發(fā)請求

2025-04-29 08:15:00

超大文件流式 + yield日志

2024-05-20 08:06:42

ASP接口服務

2021-10-26 10:28:41

開發(fā)架構(gòu)Kubernetes

2009-12-11 17:39:47

VS 2008數(shù)據(jù)

2025-02-13 09:02:04

2014-07-04 09:47:24

SwiftSwift開發(fā)

2017-04-12 11:16:08

Python終端編程

2021-09-08 09:41:09

開發(fā)Go代碼

2025-02-05 08:43:40

2022-06-27 09:00:55

SwiftGit Hooks

2019-03-11 09:18:20

Java 8Stream數(shù)據(jù)結(jié)構(gòu)
點贊
收藏

51CTO技術棧公眾號