Four ways to parse JSON in iOS

Source: Internet
Author: User
Tags uikit

As a lightweight data interchange format, JSON is gradually replacing XML as a common format for network data.

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

Main code in File VIEWCONTROLLER.M:

(1) using Touchjson parsing method: (Need to import Package: #import "Touchjson/json/cjsondeserializer.h")

[CPP]View Plaincopy
  1. Use Touchjson to analyze the weather in Beijing
  2. -(Ibaction) Btnpresstouchjson: (ID) Sender {
  3. //Get API Interface
  4. Nsurl *url = [Nsurl urlwithstring:@"http://m.weather.com.cn/data/101010100.html"];
  5. //Define a Nserror object for capturing error messages
  6. Nserror *error;
  7. NSString *jsonstring = [NSString stringwithcontentsofurl:url encoding:nsutf8stringencoding error:&error];
  8. NSLog (@"jsonstring--->%@", jsonstring);
  9. //The parsed content is stored in the dictionary, the encoding format is UTF8, and prevents garbled characters when the value is not taken .
  10. Nsdictionary *rootdic = [[Cjsondeserializer deserializer] deserialize:[jsonstring datausingencoding: Nsutf8stringencoding] error:&error];
  11. //Because the JSON file returned has two layers, go to the second layer of content into the dictionary
  12. Nsdictionary *weatherinfo = [rootdic objectforkey:@"Weatherinfo"];
  13. NSLog (@"Weatherinfo--->%@", weatherinfo);
  14. //Value printing
  15. 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 "];
  16. }

(2) using Sbjson parsing method: (Need to import Package: #import "Sbjson/sbjson.h")

[CPP]View Plaincopy
  1. Using Sbjson to analyze the weather in Nanyang
  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 is%@%@%@ weather conditions are:%@%@", [Weatherinfo objectforkey:@"date_y"],[ Weatherinfo objectforkey:@"Week"],[weatherinfo objectforkey:@"City"], [Weatherinfo objectforkey:@]  Weather1 "], [Weatherinfo objectforkey:@" Temp1 "];
  10. }

(3) parsing with IOS5 self-parsing class Nsjsonserialization method: (No import package, IOS5 support, low version iOS not supported)

[CPP]View Plaincopy
  1. -(Ibaction) Btnpressios5json: (ID) Sender {
  2. Nserror *error;
  3. //Load a Nsurl object
  4. Nsurlrequest *request = [nsurlrequest requestwithurl:[nsurl urlwithstring:@"http://m.weather.com.cn/data/  101180601.html "];
  5. //Put the requested URL data into the NSData object
  6. NSData *response = [nsurlconnection sendsynchronousrequest:request returningresponse:nil Error:nil];
  7. //IOS5 self-contained parsing class Nsjsonserialization parse data from response into a dictionary
  8. Nsdictionary *weatherdic = [nsjsonserialization jsonobjectwithdata:response options:nsjsonreadingmutableleaves Error :&error];
  9. Nsdictionary *weatherinfo = [weatherdic objectforkey:@"Weatherinfo"];
  10. 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 "];
  11. NSLog (@"Weatherinfo dictionary content is--"%@ ", weatherdic);
  12. }

(4) Parsing method using Jsonkit : (Need to import Package: #import "Jsonkit/jsonkit.h")

[CPP]View Plaincopy
  1. -(Ibaction) Btnpressjsonkit: (ID) Sender {
  2. //If JSON is "single-layer", that is, value is a string, a number, 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, 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:
  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. }


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

Original: http://blog.csdn.net/enuola/article/details/7903632/

Four ways to parse JSON in iOS

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.