Explanation of four JSON data parsing methods for iOS

Source: Internet
Author: User

Many data transmission formats in the network are JSON or XML. XML has been introduced in previous blog posts. This article introduces JSON data.

There are four methods to choose from when parsing JSON data, includingNativeNsjsonserialization, touchjson, jsonkit, sbjonThe last three methods must be imported to a third-party class library. (When using a third-party class library, if the project supports the arc, and these class library files do not support the arc feature, the arc problem will occur, so we need to add the arc feature, add-fno-objc-arc)

Appendix:

Touchjson package download: http://download.csdn.net/detail/enuola/4523169SBJson package download: customized

I. Native nsjsonserialization usage details.

You use the nsjsonserialization class to convert JSON to foundation objects and convert Foundation objects to JSON.
An object that may be converted to JSON must have the following properties: // but the object converted to JSON must have the following attributes:
The top level object is an nsarray or nsdictionary. // the top level object must be nsarray or nsdictionary.
All objects are instances of nsstring, nsnumber, nsarray, nsdictionary, or nsnull. // all objects must be nsstring, nsnumber, nsarray, nsdictionary, and nsnull instances.
All dictionary keys are instances of nsstring. // All nsdictionary keys must be of the nsstring type.
Numbers are not Nan or infinity. // numeric objects cannot be non-numeric or infinite
Other rules may apply. Calling isvalidjsonobject: or attempting a conversion are the definitive ways to tell if a given object can be converted to JSON data.

This is the first section of the nsjsonserialization official document.Nsjsonserialization can convert a JSON object to a foundation object, or convert a foundation object to a JSON object.. However, the above requirements are met when converting the foundation object to a JSON object. Note thatThe
Top level object is an nsarray or nsdictionary.

The corresponding methods of this class include:

Creating a JSON Object+ JSONObjectWithData:options:error:+ JSONObjectWithStream:options:error:Creating JSON Data+ dataWithJSONObject:options:error:+ writeJSONObject:toStream:options:error:+ isValidJSONObject:

The method marked in red is a common method, and its usage is shown below. Note the parameter types in each method.

Returns a Foundation object from given JSON data.+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error

The nsjsonreadingoptions includes:

NSJSONReadingMutableContainersSpecifies that arrays and dictionaries are created as mutable objects.NSJSONReadingMutableLeavesSpecifies that leaf strings in the JSON object graph are created as instances of NSMutableString.NSJSONReadingAllowFragmentsSpecifies that the parser should allow top-level objects that are not an instance of NSArray or NSDictionary.
Returns a Boolean value that indicates whether a given object can be converted to JSON data.+ (BOOL)isValidJSONObject:(id)obj
Returns JSON data from a Foundation object.+ (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error

Among them, nsjsonwritingoptions includes

NSJSONWritingPrettyPrintedSpecifies that the JSON data should be generated with whitespace designed to make the output more readable. If this option is not set, the most compact possible JSON representation is generated.

The following is a simple program example to illustrate this process.

NSDictionary *jsonDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"value1",@"key1",@"value2",@"key2", nil];    NSError *error;    NSData *jsonData;    if ([NSJSONSerialization isValidJSONObject:jsonDictionary]) {        NSLog(@"yes");        jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONWritingPrettyPrinted error:&error];    }    else {        NSLog(@"error :%@",error.localizedDescription);    }    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:&error];    NSLog(@"key1: %@",[dictionary objectForKey:@"key1"]);

Ii. Usage of jsonkit(I currently use jsonkit to parse strings in JSON format)

To use jsonkit, You need to import the jsonkit class library file in the project. You can download the file from the above link.

Jsonkit is commonly used in data parsing (both instance methods:

- (id)objectFromJSONString;- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags;- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;- (id)mutableObjectFromJSONString;- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags;- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;

- (id)objectFromJSONData;- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags;- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;- (id)mutableObjectFromJSONData;- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags;- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;

The first three are commonly used.

Among them, jkparseoptionflags includes:

Jkserializeoptionnone = 0,
Jkserializeoptionpretty = (1 <0 ),
Jkserializeoptionescapeunicode = (1 <1 ),
Jkserializeoptionescapeforwardslashes = (1 <4 ),
Jkserializeoptionvalidflags = (jkserializeoptionpretty | jkserializeoptionescapeunicode | jkserializeoptionescapeforwardslashes ),

The following code demonstrates the JSON format of the parsing string:

NSString *jsonString =@"[{\"precision\": \"zip\",\"Latitude\":  37.7668,\"Longitude\": -122.3959,\"Address\":   \"\",\"City\":      \"SAN FRANCISCO\",\"State\":     \"CA\",\"Zip\":       \"94107\",\"Country\":   \"US\"},{\"precision\": \"zip\",\"Latitude\":  37.371991,\"Longitude\": -122.026020,\"Address\":   \"\",\"City\":      \"SUNNYVALE\",\"State\":     \"CA\",\"Zip\":       \"94085\",\"Country\":   \"US\"}]";    NSArray *jsonArray = [jsonString objectFromJSONString];    for(NSDictionary *dictionary in jsonArray) {        NSLog(@"City :%@",[dictionary objectForKey:@"City"]);    }

The jsonstring contains the following content (there are two dictionary items, so we can use an array for loading and then use the dictionary to load the content separately ):

  [    {        \"precision\": \"zip\",        \"Latitude\": 37.7668,        \"Longitude\": -122.3959,        \"Address\": \"\",        \"City\": \"SANFRANCISCO\",        \"State\": \"CA\",        \"Zip\": \"94107\",        \"Country\": \"US\"    },    {        \"precision\": \"zip\",        \"Latitude\": 37.371991,        \"Longitude\": -122.026020,        \"Address\": \"\",        \"City\": \"SUNNYVALE\",        \"State\": \"CA\",        \"Zip\": \"94085\",        \"Country\": \"US\"    }    ] 

Iii. touchjson usage

Download the Library Based on the download link provided above, decompress the library, and import it to the source folder in the project. The following import files are required for use.

#import "Source/JSON/CJSONDeserializer.h"#import "Source/JSON/CJSONSerializer.h"

Tip: For an arc project, add arc:-fno-objc-arc to all touchjson files in target.

According to the preceding Import Statement, this database can be used to convert JSON data into other objects or serialize data to convert an object into JSON data.

1. Let's take a look at the method corresponding to the serialization operation! You can find it in the cjsonserializer. h file.

    + (CJSONSerializer *)serializer;     - (BOOL)isValidJSONObject:(id)inObject;     /// Take any JSON compatible object (generally NSNull, NSNumber, NSString, NSArray and NSDictionary) and produce an NSData containing the serialized JSON.     - (NSData *)serializeObject:(id)inObject error:(NSError **)outError;     - (NSData *)serializeNull:(NSNull *)inNull error:(NSError **)outError;     - (NSData *)serializeNumber:(NSNumber *)inNumber error:(NSError **)outError;     - (NSData *)serializeString:(NSString *)inString error:(NSError **)outError;     - (NSData *)serializeArray:(NSArray *)inArray error:(NSError **)outError;     - (NSData *)serializeDictionary:(NSDictionary *)inDictionary error:(NSError **)outError;

The first three methods are commonly used. Note: Take any JSON compatible object (generally nsnull, nsnumber, nsstring, nsarray and nsdictionary) and produce an nsdata containing the serialized JSON. let's take a look at the instance code!

 NSError *error;    NSString *jsonString =@"{\"key1\":{\"precision\": \"zip\",\"Latitude\":  37.7668,\"Longitude\": -122.3959,\"Address\":   \"\",\"City\":      \"SAN FRANCISCO\",\"State\":     \"CA\",\"Zip\":       \"94107\",\"Country\":   \"US\"},\"key2\":{\"precision\": \"zip\",\"Latitude\":  37.371991,\"Longitude\": -122.026020,\"Address\":   \"\",\"City\":      \"SUNNYVALE\",\"State\":     \"CA\",\"Zip\":       \"94085\",\"Country\":   \"US\"}}";       CJSONSerializer *serial = [CJSONSerializer serializer];  //creat an object of CJSONSerializer    if ([serial isValidJSONObject:jsonString]) {        NSLog(@"yes");        NSData *jsonData = [serial serializeString:jsonString error:&error];        }        }

2. The next step is the deserialization operation (data parsing). We can see the corresponding method in the cjsondeserializer. h file.

 + (CJSONDeserializer *)deserializer;     - (id)deserialize:(NSData *)inData error:(NSError **)outError;     - (id)deserializeAsDictionary:(NSData *)inData error:(NSError **)outError;     - (id)deserializeAsArray:(NSData *)inData error:(NSError **)outError;

It is easy to understand, and the first two are commonly used. Let's look at the instance code!

NSString *jsonString =@"{\"key1\":{\"precision\": \"zip\",\"Latitude\":  37.7668,\"Longitude\": -122.3959,\"Address\":   \"\",\"City\":      \"SAN FRANCISCO\",\"State\":     \"CA\",\"Zip\":       \"94107\",\"Country\":   \"US\"},\"key2\":{\"precision\": \"zip\",\"Latitude\":  37.371991,\"Longitude\": -122.026020,\"Address\":   \"\",\"City\":      \"SUNNYVALE\",\"State\":     \"CA\",\"Zip\":       \"94085\",\"Country\":   \"US\"}}";    NSError *error;    NSArray *array = [[CJSONDeserializer deserializer] deserialize:[jsonString dataUsingEncoding:NSUTF8StringEncoding] error:&error];    for(NSDictionary *dic in array) {        NSLog(@"City :%@",[dic objectForKey:@"City"]);    }

The above code encodes a JSON string into the jsona format, and then parses it, that is, deserialization.

Iv. sbjson usage

When using sbjson to parse data, you need to import the corresponding file and # import "sbjson/sbjsonparser. H". The main methods used include:

- (id)objectWithData:(NSData*)data;- (id)objectWithString:(NSString *)repr;- (id)objectWithString:(NSString*)jsonText                 error:(NSError**)error;

The following example shows how to use sbjson to parse data.

NSString *jsonString =@"{\"key1\":{\"precision\": \"zip\",\"Latitude\":  37.7668,\"Longitude\": -122.3959,\"Address\":   \"\",\"City\":      \"SAN FRANCISCO\",\"State\":     \"CA\",\"Zip\":       \"94107\",\"Country\":   \"US\"},\"key2\":{\"precision\": \"zip\",\"Latitude\":  37.371991,\"Longitude\": -122.026020,\"Address\":   \"\",\"City\":      \"SUNNYVALE\",\"State\":     \"CA\",\"Zip\":       \"94085\",\"Country\":   \"US\"}}";    NSError *error;    SBJsonParser *parser = [[SBJsonParser alloc] init];    NSDictionary *dictionary= [parser objectWithString:jsonString error:&error];    NSLog(@"%@",dictionary);    NSLog(@"%@",[[dictionary objectForKey:@"key1"] objectForKey:@"City"]);

To explain, the jsonstring here is a little different from the previous one. You will be able to see the output later (key1 and key2 are added to the two dictionaries ).

Create an sbjsonparser object and call the method for parsing.

{    key1 =     {        Address = "";        City = "SAN FRANCISCO";        Country = US;        Latitude = "37.7668";        Longitude = "-122.3959";        State = CA;        Zip = 94107;        precision = zip;    };    key2 =     {        Address = "";        City = SUNNYVALE;        Country = US;        Latitude = "37.371991";        Longitude = "-122.02602";        State = CA;        Zip = 94085;        precision = zip;    };}


Test results show that the system's native API is the fastest to parse, so it should be the first choice in the Project, and the sbjson parsing speed is poor, which is closer to the native API is jsonkit.

End introduction!

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.