Four Json parsing methods in IOS

Source: Internet
Author: User

As a lightweight data exchange format, json is gradually replacing xml and becoming a common format for network data.

Some json code formats are messy. You can use this "http://www.bejson.com/# 网 to perform the jsonformat verification (click to open the link ). This website not only detects errors in Json code, but also displays json data in a view, which is convenient.

APPLE has provided native support for json (NSJSONSerialization) Since IOS5. However, to be compatible with previous ios versions, you can use a third-party library to parse Json.

This article introducesTouchJson,
SBJson, JSONKit, and
Native json method supported by iOS5
, Parse the National Meteorological Administration API, TouchJson and SBJson need to download their library

TouchJson package download: http://download.csdn.net/detail/enuola/4523169

SBJson
Package download: http://download.csdn.net/detail/enuola/4523177

JSONKit package download: http://download.csdn.net/detail/enuola/4523160

The following complete program source package download: http://download.csdn.net/detail/enuola/4523223

PS:

Weather forecast interface provided by the National Meteorological Administration

There are three interface addresses:

Http://www.weather.com.cn/data/sk/101010100.html

Http://www.weather.com.cn/data/cityinfo/101010100.html

Http://m.weather.com.cn/data/101010100.html

The third interface is more detailed. It provides 6-day weather. For details about the information returned by the API, see the open-source free weather forecast API and code for all regions in China !! (Provided by the National Meteorological Administration), each city in China corresponds to this id. Based on the changed id, we can parse the corresponding weather in each city;

The following describes four methods to parse JSON:

First, create a new project (do not select the ARC mechanism) and add the following controls:

As shown in. The program code is shown below:

In the ViewController. h file:

[Cpp]View plaincopyprint?
  1. # Import <UIKit/UIKit. h>
  2. @ Interface ViewController: UIViewController
  3. @ Property (retain, nonatomic) IBOutlet UITextView * txtView;
  4. -(IBAction) btnPressTouchJson :( id) sender;
  5. -(IBAction) btnPressSBJson :( id) sender;
  6. -(IBAction) btnPressIOS5Json :( id) sender;
  7. -(IBAction) btnPressJsonKit :( id) sender;
  8. @ End
#import <UIKit/UIKit.h>@interface ViewController : UIViewController@property (retain, nonatomic) IBOutlet UITextView *txtView;- (IBAction)btnPressTouchJson:(id)sender;- (IBAction)btnPressSBJson:(id)sender;- (IBAction)btnPressIOS5Json:(id)sender;- (IBAction)btnPressJsonKit:(id)sender; @end

Main code in the ViewController. m file:

(1) UseTouchJSonResolution Method: (import the package: # import "TouchJson/JSON/CJSONDeserializer. h ")

 

[Cpp]View plaincopyprint?
  1. // Use TouchJson to parse weather conditions in Beijing
  2. -(IBAction) btnPressTouchJson :( id) sender {
  3. // Obtain the API
  4. NSURL * url = [NSURL URLWithString: @ "http://m.weather.com.cn/data/101010100.html"];
  5. // Define an NSError object to capture error information
  6. NSError * error;
  7. NSString * jsonString = [NSString stringWithContentsOfURL: url encoding: NSUTF8StringEncoding error: & error];
  8. NSLog (@ "jsonString ---> % @", jsonString );
  9. // Store the parsed content in the dictionary. The encoding format is UTF8 to prevent garbled Characters During the value.
  10. NSDictionary * rootDic = [[CJSONDeserializer deserializer] deserialize: [jsonString dataUsingEncoding: NSUTF8StringEncoding] error: & error];
  11. // Because the returned Json file contains two layers, go to the second layer and put the content in the dictionary.
  12. NSDictionary * weatherInfo = [rootDic objectForKey: @ "weatherinfo"];
  13. NSLog (@ "weatherInfo ---> % @", weatherInfo );
  14. // Print the value
  15. TxtView. text = [NSString stringWithFormat: @ "today's weather conditions are: % @", [weatherInfo objectForKey: @ "date_y"], [weatherInfo objectForKey: @ "week"], [weatherInfo objectForKey: @ "city"], [weatherInfo objectForKey: @ "weather1"], [weatherInfo objectForKey: @ "temp1"];
  16. }
// Use TouchJson to parse the weather in Beijing-(IBAction) btnPressTouchJson :( id) sender {// get API interface NSURL * url = [NSURL URLWithString: @ "http://m.weather.com.cn/data/101010100.html"]; // define an NSError object to capture the error message NSError * error; NSString * jsonString = [NSString stringWithContentsOfURL: url encoding: NSUTF8StringEncoding error: & error]; NSLog (@ "jsonString ---> % @", jsonString); // store the parsed content in the dictionary. The encoding format is UTF8, prevent garbled NSDictionary * rootDic = [[CJSONDeserializer deserializer] deserialize: [jsonString dataUsingEncoding: NSUTF8StringEncoding] error: & error]; // The returned Json file has two layers, go to the second layer and put the content in the dictionary to NSDictionary * weatherInfo = [rootDic objectForKey: @ "weatherinfo"]; NSLog (@ "weatherInfo --- >%@", weatherInfo ); // print txtView. text = [NSString stringWithFormat: @ "today's weather conditions are: % @", [weatherInfo objectForKey: @ "date_y"], [weatherInfo objectForKey: @ "week"], [weatherInfo objectForKey: @ "city"], [weatherInfo objectForKey: @ "weather1"], [weatherInfo objectForKey: @ "temp1"];}

(2) UseSBJsonResolution Method: (import the package: # import "SBJson/SBJson. h ")

 

 

[Cpp]View plaincopyprint?
  1. // Parse the weather in Nanyang using SBJson
  2. -(IBAction) btnPressSBJson :( id) sender {
  3. NSURL * url = [NSURL URLWithString: @ "http://m.weather.com.cn/data/101180701.html"];
  4. NSError * error = nil;
  5. NSString * jsonString = [NSString stringWithContentsOfURL: url encoding: NSUTF8StringEncoding error: & error];
  6. SBJsonParser * parser = [[SBJsonParser alloc] init];
  7. NSDictionary * rootDic = [parser objectWithString: jsonString error: & error];
  8. NSDictionary * weatherInfo = [rootDic objectForKey: @ "weatherinfo"];
  9. TxtView. text = [NSString stringWithFormat: @ "today's weather conditions are: % @", [weatherInfo objectForKey: @ "date_y"], [weatherInfo objectForKey: @ "week"], [weatherInfo objectForKey: @ "city"], [weatherInfo objectForKey: @ "weather1"], [weatherInfo objectForKey: @ "temp1"];
  10. }
// Use SBJson to parse the weather in Nanyang-(IBAction) btnPressSBJson :( id) sender {NSURL * url = [NSURL URLWithString: @ "http://m.weather.com.cn/data/101180701.html"]; NSError * error = nil; NSString * jsonString = [NSString stringWithContentsOfURL: url encoding: Unknown error: & error]; SBJsonParser * parser = [[SBJsonParser alloc] init]; NSDictionary * rootDic = [parser objectWithString: jsonString error: & error]; NSDictionary * weatherInfo = [rootDic objectForKey: @ "weatherinfo"]; txtView. text = [NSString stringWithFormat: @ "today's weather conditions are: % @", [weatherInfo objectForKey: @ "date_y"], [weatherInfo objectForKey: @ "week"], [weatherInfo objectForKey: @ "city"], [weatherInfo objectForKey: @ "weather1"], [weatherInfo objectForKey: @ "temp1"];}

(3) UseBuilt-in parsing class NSJSONSerialization for IOS5Method resolution: (no package needs to be imported, supported by IOS5, not supported by IOS in earlier versions)

 

 

[Cpp]View plaincopyprint?
  1. -(IBAction) btnPressIOS5Json :( id) sender {
  2. NSError * error;
  3. // Load an NSURL object
  4. NSURLRequest * request = [NSURLRequest requestWithURL: [NSURL URLWithString: @ "http://m.weather.com.cn/data/101180601.html"];
  5. // Put the requested url data in the NSData object
  6. NSData * response = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
  7. // The built-in parsing class NSJSONSerialization of IOS5 parses the data from response and puts it in the dictionary
  8. NSDictionary * weatherDic = [NSJSONSerialization JSONObjectWithData: response options: NSJSONReadingMutableLeaves error: & error];
  9. NSDictionary * weatherInfo = [weatherDic objectForKey: @ "weatherinfo"];
  10. TxtView. text = [NSString stringWithFormat: @ "today's weather conditions are: % @", [weatherInfo objectForKey: @ "date_y"], [weatherInfo objectForKey: @ "week"], [weatherInfo objectForKey: @ "city"], [weatherInfo objectForKey: @ "weather1"], [weatherInfo objectForKey: @ "temp1"];
  11. NSLog (@ "the content in weatherInfo dictionary is --" % @ ", weatherDic );
  12. }
-(IBAction) btnPressIOS5Json :( id) sender {NSError * error; // load an NSURL object NSURLRequest * request = [NSURLRequest requestWithURL: [NSURL URLWithString: @ "http://m.weather.com.cn/data/101180601.html"]; // put the request url data in the NSData object NSData * response = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil]; // NSDictionary * weatherDic = [NSJSONSerialization JSONObjectWithData: response options: nsjsonreadingmutablaves error: & error]; NSDictionary * weatherInfo = [weatherDic objectForKey: @ "weatherinfo"]; txtView. text = [NSString stringWithFormat: @ "today's weather conditions are: % @", [weatherInfo objectForKey: @ "date_y"], [weatherInfo objectForKey: @ "week"], [weatherInfo objectForKey: @ "city"], [weatherInfo objectForKey: @ "weather1"], [weatherInfo objectForKey: @ "temp1"]; NSLog (@ "weatherInfo dictionary content: --" % @ ", weatherDic );}

(4) useJSONKit(Import the package: # import "JSONKit/JSONKit. h ")

 

 

[Cpp]View plaincopyprint?
  1. -(IBAction) btnPressJsonKit :( id) sender {
  2. // If json is a "single layer", that is, the values are strings and numbers, you can use objectFromJSONString
  3. NSString * json1 = @ "{\" a \ ": 123, \" B \ ": \" abc \"}";
  4. NSLog (@ "json1: % @", json1 );
  5. NSDictionary * data1 = [json1 objectFromJSONString];
  6. NSLog (@ "json1.a: % @", [data1 objectForKey: @ "a"]);
  7. NSLog (@ "json1. B: % @", [data1 objectForKey: @ "B"]);
  8. [Json1 release];
  9. // If json is nested, that is, the value contains arrays and objects. If objectFromJSONString is used again, the program may report an error (the test result shows: an error is reported when you use the json generated by php/json_encode on the network, but the resolution is successful when you use the json string defined by NSString). It is best to use objectFromJSONStringWithParseOptions:
  10. NSString * json2 = @ "{\" a \ ": 123, \" B \ ": \" abc \ ", \" c \ ": [456, \ "hello \"], \ "d \": {\ "name \": \ "Zhang San \", \ "age \": \ "32 \"}}";
  11. NSLog (@ "json2: % @", json2 );
  12. NSDictionary * data2 = [json2 objectFromJSONStringWithParseOptions: JKParseOptionLooseUnicode];
  13. NSLog (@ "json2.c: % @", [data2 objectForKey: @ "c"]);
  14. NSLog (@ "json2.d: % @", [data2 objectForKey: @ "d"]);
  15. [Json2 release];
  16. }
-(IBAction) btnPressJsonKit :( id) sender {// If json is a "single layer", that is, the values are strings and numbers, you can use objectFromJSONString NSString * json1 = @ "{\" a \ ": 123, \" B \ ": \" abc \ "}"; NSLog (@ "json1: % @ ", json1); NSDictionary * data1 = [json1 objectFromJSONString]; NSLog (@" json1.a: % @ ", [data1 objectForKey: @" a "]); NSLog (@ "json1. B: % @", [data1 objectForKey: @ "B"]); [json1 release]; // If json is nested, that is, the value contains arrays and objects. If objectFromJSONString is used again, the program may report an error (the test result shows that an error is reported when the json file generated by php/json_encode is used on the network or obtained, but when using the json string defined by NSString, the resolution is successful.) it is best to use objectFromJSONStringWithParseOptions: NSString * json2 = @ "{\" a \ ": 123, \" B \": \ "abc \", \ "c \": [456, \ "hello \"], \ "d \": {\ "name \": \ "Zhang San \", \ "age \": \ "32 \"} "; NSLog (@" json2: % @ ", json2 ); NSDictionary * data2 = [json2 UNICODE: JKParseOptionLooseUnicode]; NSLog (@ "json2.c: % @", [data2 objectForKey: @ "c"]); NSLog (@ "json2.d: % @ ", [data2 objectForKey: @" d "]); [json2 release];}

In addition, because iOS5 has added the JSON parsing API, we tested the parsing speed with the other five open-source JSON parsing libraries. The following is the test result.

 

The selected test object includes the following frameworks. NSJSONSerialization is a JSON-parsed API added by the iOS5 system and requires an iOS5 environment. If you perform a test in a lower version, code calls should be blocked.

-[SBJSON (json-framework)] (http://code.google.com/p/json-framework)

-[TouchJSON (from touchcode)] (http://code.google.com/p/touchcode)

-[YAJL (objective-C bindings)] (http://github.com/gabriel/yajl-objc)

-[JSONKit] (https://github.com/johnezang/JSONKit)

-[NextiveJson] (https://github.com/nextive/NextiveJson)

-[NSJSONSerialization] (http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40010946)

We selected four files containing json data for testing. Each file performs 100 parsing actions to compare the parsing time.

.....

The test results show that the system's API parsing speed is the fastest. We chose to use it in engineering projects. The SBJSON parsing speed, which is widely used, is the second to the last, which surprised me.

JSONKit is closer to the system API.

 

There is no comparison between open APIs and usage methods. If the test is based solely on the above resolution speed:

1: iOS5 should select the system API

2: if you cannot use system APIs, select JSONKit.

Related Article

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.