Parsing of the "iOS Development objective-c" JSON

Source: Internet
Author: User

First, what is JSON?
About the JSON explanation or to see how Baidu Encyclopedia explains the "Baidu Encyclopedia---JSON", here is more professional. First we already know what our object is and know some of its basic format (Baidu Encyclopedia has a description).
Let's take a look at a JSON file that I've saved locally to specifically analyze its format.

First select "Outline" mode in the upper left corner, we see three columns from left to right, respectively, "type"---type, "value"---value and "name"---name. There is also a triangular arrow in front of "Name", which can be opened to see what it is.

Inside is the data in the form of a string, and there is nothing in it. Some of the others are in the same form.
We can also view this JSON document by selecting the text mode in the upper left corner.

See no value inside the contents of the form are the same.
The structure of this JSON file is roughly the same:
The outermost is a dictionary, the Dictionary of a key CATALOG corresponding to the Vaule CD is an array, the array has 25 elements, each element is a dictionary, the dictionary is six key-value pairs. This is the structure of this JSON file.
Second, the JSON parsing
The parsing of JSON in Xcode is actually a simple three-step.
The first step: Convert the String form link to the URL form;
The second step: use NSData to send the request download data to the server, conversion to save as NSData form;
Step three: Call the System class Nsjsonserialization + (ID) jsonobjectwithdata: (NSData *) Data options: (nsjsonreadingoptions) opt error: ( Nserror *) error; Stores the returned data as an array or dictionary. Why arrays and dictionaries?
In Xcode we can find such a method inside the Nsjsonserialization class:
/* Returns YES If the given object can be converted to JSON data, NO otherwise. The object must has the following properties:-Top level object is a Nsarray or Nsdictionary-all objects is nsstring, NSNumber, Nsarray, nsdictionary, or Nsnull-all dictionary keys are nsstrings-nsnumbers is not NaN or Infinityother rule s may apply. Calling this method or attempting a conversion is the definitive ways to tell if a given object can be converted to JSON data.*/+ (BOOL) Isvalidjsonobject: (id) obj;

This method is used to determine if an object is not a JSON, and returns Yes if it is, otherwise it returns No. Take a look at the description of line four that begins with "-".
The first sentence: outermost is not an array is a dictionary
The second sentence: All objects are NSString, NSNumber, Nsarray, nsdictionary, or NSNull type, (also including bool type)
The third sentence: All dictionary keys are of type NSString
The nsnumbers is not Nan (not knowing his explanation) or infinity
This method also tells us why the outermost layer of JSON is the array or the type of values in the dictionary and JSON.
So how does the three-step code for parsing work? In fact, in the code to write a little more than three lines of code.
Nsurl * url = [Nsurl urlwithstring:path];//The string type is the path to the Nsurl type of nsdata * data = [NSData datawithcontentsofurl:url];/to the from URL Data, nsdictionary * dic = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutablecontainers Error: nil];//uses a dictionary to receive the returned data.

Why is the parameter inside the method like this? We can find the official explanation of the corresponding method. We just have to hold down the keyboard "command" key, the mouse to move to the method there, click on it can automatically jump to the corresponding method of the declaration there.
/* Create a Foundation object from JSON data. Set the nsjsonreadingallowfragments option if the parser should allow top-level objects that is not an nsarray or nsdicti Onary. Setting the nsjsonreadingmutablecontainers option would make the parser generate mutable nsarrays and nsdictionaries. Setting the nsjsonreadingmutableleaves option would make the parser generate mutable nsstring objects. If An error occurs during the parse, then the error parameter would be set and the result would be nil. The data must is in one of the 5 supported encodings listed in the JSON specification:utf-8, Utf-16le, Utf-16be, Utf-32le , Utf-32be. The data may or could not be a BOM. The most efficient encoding to use for parsing are UTF-8, so if you had a choice in encoding the data passed to this Metho D, use utf-8.*/+ (ID) jsonobjectwithdata: (NSData *) Data options: (nsjsonreadingoptions) opt error: (NSERROR *) error; 
The rest of the work is not difficult to complete. is how to get the data we need from the returned dictionary. These are not very much related to the parsing of JSON. Just sort out the hierarchy and take 1.1 points.
Get the data inside the dictionary we can build a model to get. In this JSON file, each album has six members, so we can build the model as an album. You can then store the models in an array.
III. Building Models
The above has shown that the JSON inside the characteristics of the data and structure of the law, the following model is not difficult to build, we look directly at the code.
① establishes a model class Datamodel, which has six members:
@property (nonatomic,copy) NSString * ARTIST; Artist @property (nonatomic,copy) NSString * Company; Company @property (nonatomic,copy) nsstring * country; National @property (nonatomic,copy) nsstring * PRICE; Price @property (nonatomic,copy) NSString * TITLE; Album name @property (nonatomic,copy) nsstring * year; Age
We will then parse the JSON class to declare a mutable array-(Nsarray *) Preasejson;
The next is the parsed code and the model data are packaged. This code is not difficult to understand.
-(Nsarray *) Preasejson{/****************************json parsing *************************************/nsurl * url = [ Nsurl Urlwithstring:path]; NSData * data = [NSData Datawithcontentsofurl:url]; Nsdictionary * dic = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutablecontainers Error:nil]; Nsarray * Cdarr = dic[@ "CATALOG"][@ "CD"]; Traverse the CD corresponding to the array for (Nsdictionary * di in Cdarr) {Datamodel * mo = [[Datamodel alloc] init];//mo. ARTIST = di[@ "ARTIST"];// = di[@ "Company"];//mo. Country = di[@ "Country"];//mo. Price = di[@ "Price"];//mo. title = di[@ "title"];//mo. Year = di[@];//[_arr addobject:mo];//KVC (Key---value encoding)//This method and the above annotated method two select one, use this method to implement a printing method in the data model (this printing method can not), and the name of the member declared above must be the same as the key name in the dictionary. [Mo Setvaluesforkeyswithdictionary:di]; [_arr Addobject:mo];} return _arr;}

Finally, it's printed.
-(void) Print{myjson * Myjson = [[Myjson alloc] init]; Nsarray * array = [Myjson preasejson];int i = 0;for (Datamodel * DM in array) {printf ("-------------%d-------------\ n", + +i);p rintf ("ARTIST:%s\n", [[DM ARTIST] utf8string]); Artist printf ("Company:%s\n", [[DM] utf8string]);//record company printf ("Country:%s\n", [[DM Country] utf8string]);// State printf ("Price:%s\n", [[DM Price] utf8string]); Price printf ("title:%s\n", [[DM TITLE] utf8string]); Album name printf ("Year:%s\n", [[DM Year] utf8string]); Age//[DM show]; This show method also encapsulates the above 6 lines of printf}}+ (void) Test{myjson * js = [[Myjson alloc] init];[ JS print];}
Finally, there is only one statement in the main function: [Myjson test];
So the data is basically parsed out. Final print Result: altogether 25.

If we want to save the data in a TXT document, we need the file operation. A way to file operations is described earlier, and now you can describe a way to manipulate files.
Four, Nsfilemanager class
In fact, the operation of the file here is not difficult, the amount of code is not very large.
+ (void) Datapacket{myjson * json = [[Myjson alloc] init]; Nsarray * Dataarr = [json Preasejson]; The parsed data model is stored in array dataarr nsmutablestring * str = [[Nsmutablestring alloc] init];//new variable string Nsfilemanager * myFile = [nsfile Manager Defaultmanager];int i = 0;for (Datamodel * MD in Dataarr) {[str appendformat:@ '%d%@ ', ++i,@ '---------------------- -------\ n "]; [Str appendformat:@ "%@%@%@", @ "ARTIST:", Md. artist,@ "\ n"]; [Str appendformat:@ "%@%@%@", @ "Company:",,@ "\ n"]; [Str appendformat:@ "%@%@%@", @ "Country:", Md. country,@ "\ n"]; [Str appendformat:@ "%@%@%@", @ "Price:", Md. price,@ "\ n"]; [Str appendformat:@ "%@%@%@", @ "TITLE:", Md. title,@ "\ n"]; [Str appendformat:@ "%@%@%@", @ "Year:", Md. year,@ "\ n"];} NSData * data = [str datausingencoding:nsutf8stringencoding]; [MyFile Createfileatpath:savepath contents:data attributes:nil];}
The last sentence in the Savepath is the storage path, need to bring the file format, as you see the properties of a file displayed, such as:/user/desktop/123.txt.
Finally, let's open it and see that the same form of Xcode is printed. We also need to add a code in main, code I will not write.

About KVC key value coding is not very good to use, after the proficiency of the written again.

Finally upload an image about using Apple's own browser to open the JSON document garbled problem is how to solve.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Parsing of the "iOS Development objective-c" JSON

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