Optimize JSON processing in Swift

Source: Internet
Author: User

Optimize JSON processing in Swift

The use of SwiftyJSON is very simple:

A typical NSURLSessionTask crawls Twitter APIs and generates dataFromNetwork: NSData! :

The first thing you should do is initialize JSONValue:

 
 
  1. let json = JSONValue(dataFromNetwork) 

JSONValue is an enumeration type that represents a typical JSON data structure.

You can use subscripts to retrieve different values from the original JSONValue, as shown in the following code:

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

Note that userName is still a JSONValue. How can we get a string?

You can use the. string attribute to obtain the true positive value represented by JSON data.

 
 
  1. let userNameString = userName.string! 

For each JSON type, JSONValue provides an attribute to retrieve it:

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

Note that each attribute is an Optional value. This is because JSON data can contain any valid types it defines.

Therefore, we recommend that you bind the search value with 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. 

The. number attribute generates an NSNumber value, which is usually not very useful in Swift. You can use. double or. integer to get a Double value or an Int value.

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

In Swift, JSONValue is actually an enumeration:

 
 
  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.   

You can use a switch clause to obtain values more effectively:

 
 
  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)

Note that an array structure in JSON is encapsulated into a jsonarray <JSONVlaue>, which means that every element in the array is a JSONValue. Even if you extract an array from JSONValue, you can still use basic attributes to get the value of the element:

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

The same is true for objects. Therefore, the recommended method is to use the subscript of JSONValue when accessing every array and object.

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

In fact, you can use subscript to access a JSONValue without worrying about the crash caused by running errors:

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

If you use the recommended method to retrieve data, it is safe:

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

JSONValue complies with the Printable protocol, so it is easy to get JSON data in the original string:

 
 
  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. */ 

If you do not want to print it out, you can use the. description attribute to obtain the above string.

 
 
  1. let printableString = json.description 
Debugging and error handling

What if a JSON data error occurs or we mistakenly retrieve the data? You can use the if statement to test:

 
 
  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 

If we try to use the wrong key value or index to access data, the description attribute will be high and where your KeyPath has an error.

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

The development of SwiftyJSON will be released on Github. Please stay tuned to the subsequent versions.

Link: http://mobile.51cto.com/design-446157.htm

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.