Some JSON code format is confusing, you can use this "http://www.bejson.com/" Web site for JSON format check (click the Open link). This web site not only detects errors in JSON code, but also displays the contents of the data in JSON in the form of a view.
Starting with IOS5, Apple provides native support for JSON (Nsjsonserialization), but in order to be compatible with previous versions of iOS, you can use a third-party library to parse the JSON.
This article describes the native JSON methods supported by Touchjson, Sbjson, Jsonkit, and IOS5 , and parses the National Weather bureau Api,touchjson and Sbjson to download their libraries
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 full program source code package download: http://download.csdn.net/detail/enuola/4523223
Ps:
Weather interface provided by the National Weather
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 information is more detailed, provide 6 days of weather, about the information returned by the API, please see the Open source Free weather API and all the country code!! (National Weather Bureau provides), the country each city corresponds to this one ID number, according to change the ID good we can parse out each city corresponds to the weather;
Here are four ways to parse JSON:
First create a new project, (be careful not to select the ARC mechanism) to add the following controls:
As shown in. The program code is shown below:
In file ViewController.h:
[CPP]View Plaincopy
- #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 File VIEWCONTROLLER.M:
(1) using Touchjson parsing method: (Need to import Package: #import "Touchjson/json/cjsondeserializer.h")
[CPP]View Plaincopy
- Use Touchjson to analyze the weather in Beijing
- -(Ibaction) Btnpresstouchjson: (ID) Sender {
- //Get API Interface
- Nsurl *url = [Nsurl urlwithstring:@"http://m.weather.com.cn/data/101010100.html"];
- //Define a Nserror object for capturing error messages
- Nserror *error;
- NSString *jsonstring = [NSString stringwithcontentsofurl:url encoding:nsutf8stringencoding error:&error];
- NSLog (@"jsonstring--->%@", jsonstring);
- //The parsed content is stored in the dictionary, the encoding format is UTF8, and prevents garbled characters when the value is not taken .
- Nsdictionary *rootdic = [[Cjsondeserializer deserializer] deserialize:[jsonstring datausingencoding: Nsutf8stringencoding] error:&error];
- //Because the JSON file returned has two layers, go to the second layer of content into the dictionary
- Nsdictionary *weatherinfo = [rootdic objectforkey:@"Weatherinfo"];
- NSLog (@"Weatherinfo--->%@", weatherinfo);
- //Value printing
- Txtview.text = [NSString stringwithformat:@"Today is%@%@%@ weather conditions are:%@%@", [Weatherinfo objectforkey:@"date_y"],[ Weatherinfo objectforkey:@"Week"],[weatherinfo objectforkey:@"City"], [Weatherinfo objectforkey:@] Weather1 "], [Weatherinfo objectforkey:@" Temp1 "];
- }
(2) using Sbjson parsing method: (Need to import Package: #import "Sbjson/sbjson.h")
[CPP]View Plaincopy
- Using Sbjson to analyze 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: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 is%@%@%@ weather conditions are:%@%@", [Weatherinfo objectforkey:@"date_y"],[ Weatherinfo objectforkey:@"Week"],[weatherinfo objectforkey:@"City"], [Weatherinfo objectforkey:@] Weather1 "], [Weatherinfo objectforkey:@" Temp1 "];
- }
(3) parsing with IOS5 self-parsing class Nsjsonserialization method: (No import package, IOS5 support, low version iOS not supported)
[CPP]View Plaincopy
- -(Ibaction) Btnpressios5json: (ID) Sender {
- Nserror *error;
- //Load a Nsurl object
- Nsurlrequest *request = [nsurlrequest requestwithurl:[nsurl urlwithstring:@"http://m.weather.com.cn/data/ 101180601.html "];
- //Put the requested URL data into the NSData object
- NSData *response = [nsurlconnection sendsynchronousrequest:request returningresponse:nil Error:nil];
- //IOS5 self-contained parsing class Nsjsonserialization parse data from response into a dictionary
- Nsdictionary *weatherdic = [nsjsonserialization jsonobjectwithdata:response options:nsjsonreadingmutableleaves Error :&error];
- Nsdictionary *weatherinfo = [weatherdic objectforkey:@"Weatherinfo"];
- Txtview.text = [NSString stringwithformat:@"Today is%@%@%@ weather conditions are:%@%@", [Weatherinfo objectforkey:@"date_y"],[ Weatherinfo objectforkey:@"Week"],[weatherinfo objectforkey:@"City"], [Weatherinfo objectforkey:@] Weather1 "], [Weatherinfo objectforkey:@" Temp1 "];
- NSLog (@"Weatherinfo dictionary content is--"%@ ", weatherdic);
- }
(4) Parsing method using Jsonkit : (Need to import Package: #import "Jsonkit/jsonkit.h")
[CPP]View Plaincopy
- -(Ibaction) Btnpressjsonkit: (ID) Sender {
- //If JSON is "single-layer", that is, value is a string, a number, 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, there is an array, object in value, and if you use Objectfromjsonstring again, the program may error (test results indicate: Use of the network or the resulting php/json_ Encode generates an error when the JSON is generated, but when using a JSON string defined by NSString, parsing succeeds, 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];
- }
In addition, since IOS5 has added the JSON parsing API, we have tested it with five other open source JSON parsing libraries, and the test results are as follows.
The test object We selected contains the following frameworks, where Nsjsonserialization is the new JSON parsing API for the IOS5 system and requires a iOS5 environment, and if you test in a lower version, you should block the corresponding code call.
-[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 have selected four files containing JSON-formatted data for testing. Each file carries out 100 parsing actions, comparing the parsing time.
.....
The test results show that the system's API parsing speed is the fastest, we choose to use in the project, but also the application of a wide range of Sbjson resolution of the second-to-last difference, I am surprised.
Closer to the system API should be jsonkit.
There is no comparison of open interfaces and usage methods for APIs, if only for testing based on the above parsing speed:
1:IOS5 should choose the system's API for
2: The system API should not be used should be selected Jsonkit
Four ways to parse JSON in iOS