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?
- # 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
#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?
- // Use TouchJson to parse weather conditions in Beijing
- -(IBAction) btnPressTouchJson :( id) sender {
- // Obtain the API
- NSURL * url = [NSURL URLWithString: @ "http://m.weather.com.cn/data/101010100.html"];
- // Define an NSError object to capture error information
- 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 to prevent garbled Characters During the value.
- NSDictionary * rootDic = [[CJSONDeserializer deserializer] deserialize: [jsonString dataUsingEncoding: NSUTF8StringEncoding] error: & error];
- // Because the returned Json file contains two layers, go to the second layer and put the content in the dictionary.
- NSDictionary * weatherInfo = [rootDic objectForKey: @ "weatherinfo"];
- NSLog (@ "weatherInfo ---> % @", weatherInfo );
- // Print the value
- 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"];
- }
// 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?
- // Parse the weather in Nanyang using SBJson
- -(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: NSUTF8StringEncoding 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"];
- }
// 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?
- -(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 requested url data in the NSData object
- NSData * response = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
- // The built-in parsing class NSJSONSerialization of IOS5 parses the data from response and puts it in the dictionary
- NSDictionary * weatherDic = [NSJSONSerialization JSONObjectWithData: response options: NSJSONReadingMutableLeaves 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 (@ "the content in weatherInfo dictionary is --" % @ ", weatherDic );
- }
-(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?
- -(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: 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:
- NSString * json2 = @ "{\" a \ ": 123, \" B \ ": \" abc \ ", \" c \ ": [456, \ "hello \"], \ "d \": {\ "name \": \ "Zhang San \", \ "age \": \ "32 \"}}";
- NSLog (@ "json2: % @", json2 );
- NSDictionary * data2 = [json2 objectFromJSONStringWithParseOptions: JKParseOptionLooseUnicode];
- NSLog (@ "json2.c: % @", [data2 objectForKey: @ "c"]);
- NSLog (@ "json2.d: % @", [data2 objectForKey: @ "d"]);
- [Json2 release];
- }
-(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.