Four ways to parse JSON

Source: Internet
Author: User

1. Now that more and more of the parsing data types are JSON data, let's now parse the JSON data:

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

Download of Jsonkit Package: Https://github.com/johnezang/JSONKit

After the download is complete, we import what we need into the project:

Touchjson This package contains Touchjson and Sbjson, jsonkit to download:

Touchjson encountered problems are: Many files are not supported arc, you have to add the corresponding file:-fno-objc-arc on it.

Jsonkit: Some files also do not support arc, the same processing method to join-FNO-OBJC-ARC

Jsonkit has two more questions: Jsonkit does not support ISA

Array->isa = _jkarrayclass;

Object_setclass (array, _jkarrayclass);

Dictionary->isa = _jkdictionaryclass;

Object_setclass (dictionary, _jkdictionaryclass)

2. Begin the presentation of four data formats for parsing JSON:

To pull the interface on the story version:

The implementation files in VIEWCONTROLLER.M are as follows:

//

Viewcontroller.m

JSON parsing

#import "ViewController.h"

#import "CJSONDeserializer.h"

#import "SBJson.h"

#import "JSONKit.h"

@interface Viewcontroller ()

@property (Weak, nonatomic) Iboutlet Uitextview *textview;

@end

@implementation Viewcontroller

-(void) Viewdidload {

[Super Viewdidload];

Additional setup after loading the view, typically from a nib.

}

-(void) didreceivememorywarning {

[Super didreceivememorywarning];

Dispose of any resources the can be recreated.

}

-(Ibaction) Touchjson: (ID) Sender {

Get URL Address

Nsurl *url = [Nsurl urlwithstring:@ "http://www.weather.com.cn/data/cityinfo/101010100.html"];

Define Nserror, Catch exceptions

Nserror *error;

NSString *jsonstring = [NSString stringwithcontentsofurl:url encoding:nsutf8stringencoding error:&error];

Save data in a dictionary (parse data) utf-8 format

Nsdictionary *rootdic = [[Cjsondeserializer deserializer]deserialize:[jsonstring datausingencoding: Nsutf8stringencoding] error:&error];

The Nsdictionary dictionary contains two layers

//    {

"Weatherinfo": {

"City": "Beijing",

"Cityid": "101010100",

"Temp1": "15 ℃",

"Temp2": "5 ℃",

"Weather": "Cloudy",

"IMG1": "D1.gif",

"Img2": "N1.gif",

"Ptime": "08:00"

//        }

//    }

Nsdictionary *weatherinfo = [rootdic objectforkey:@ "Weatherinfo"];

NSLog (@ "weatheinfo:%@", weatherinfo);

Self. Textview.text = [NSString stringwithformat:@ "Today is%@%@%@ weather conditions are:%@%@", [Weatherinfo objectforkey:@ "City"],[weatherin Fo objectforkey:@ "Cityid"],[weatherinfo objectforkey:@ "Temp1"], [Weatherinfo objectforkey:@ "Temp2"], [Weatherinfo objectforkey:@ "Ptime"];

}

-(Ibaction) Sbjson: (ID) Sender {

Nsurl *url = [Nsurl urlwithstring:@ "http://www.weather.com.cn/data/cityinfo/101010100.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"];

Self. Textview.text = [NSString stringwithformat:@ "Today is%@%@%@ weather conditions are:%@%@", [Weatherinfo objectforkey:@ "City"],[weatherin Fo objectforkey:@ "Cityid"],[weatherinfo objectforkey:@ "Temp1"], [Weatherinfo objectforkey:@ "Temp2"], [Weatherinfo objectforkey:@ "Ptime"];

}

-(Ibaction) JOSN: (ID) Sender {

Nserror *error;

Loading a Nsurl Object

Nsurlrequest *request = [nsurlrequest requestwithurl:[nsurl urlwithstring:@ "Http://www.weather.com.cn/data/cityinfo /101010100.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"];

Self. Textview.text = [NSString stringwithformat:@ "Today is%@%@%@ weather conditions are:%@%@", [Weatherinfo objectforkey:@ "Date_y"],[weather Info objectforkey:@ "Week"],[weatherinfo objectforkey:@ "City"], [Weatherinfo objectforkey:@ "Weather1"], [Weatherinfo objectforkey:@ "Temp1"];

NSLog (@ "Weatherinfo dictionary content is--"%@ ", weatherdic);

}

-(Ibaction) Josnkit: (ID) Sender {

If JSON is "single-layer", that is, value is a string, a number, you can use the 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 get an error (the test results indicate that using JSON generated by the network or obtained php/json_encode will result in an error, However, when using nsstring-defined JSON strings, 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];

}

@end

Hope to help you!!

Four ways to parse JSON

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.