Comparison of XML and JSON

Source: Internet
Author: User

Brief introduction:

When data is interacting between the client and the server, the server often returns data to the client in a certain format. Generally, the data returned to the client by the server is either JSON or XML document format (except for file downloads). Each of these data formats is described below.

(a) JSON data parsing:

Characteristics:

JSON comes from the private sector and is a lightweight data format. Features: small size, fast transmission, so 80% of the data are in JSON format.

Format:

The format of JSON is much like the dictionary and array in OC, for example:

{"Name": "Jack", "Age": 10}
{"Names": ["Jack", "Rose", "Jim"]}

JSON–OC Conversion Table
----------------JSON-------------- ------------------OC------------------
------------curly Braces {}------------- --------[Email protected]{}---------
------------brackets []-------------- [Email protected] []-------------
------------double quotation mark ""-------------- [Email protected] ""------------
---------Number 10, 10.8----------- [email protected], @10.8------

A few things to note:

1. JSON in standard format:key must be in double quotation marks

2.true/false converted to OC data is the NSNumber type. True-->@1;false-->@0

3.null-->nsnull (Empty object)

Verification Method:

//stringNSString *json =@"NULL";//string --binary dataNSData *data =[JSON datausingencoding:nsutf8stringencoding];//Binary data->json data     IDobj =[nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingallowfragments Error:nil]; NSLog (@"%@", [objclass]);/*Print Result: 2015-08-28 00:23:04.393 JSON and OC objects to each other [6274:345722] NSNull*/

JSON Data parsing scheme:

In iOS, there are 4 common parsing scenarios for JSON, and these 4 parsing scenarios can be divided into two categories.

First Category: Third-party frameworks: Jsonkit, Sbjson, Touchjson (performance from left to right, worse)

Type II: Apple Native (comes with): Nsjsonserialization (Best performance)

Common two ways to Nsjsonserialization:

OC Object (nsdata), JSON data (Foundation object)

// JSON data, OC Object + (ID) Jsonobjectwithdata: (NSData *) Data options: (nsjsonreadingoptions) opt error: ( Nserror * *) error;
    • Nsjsonreadingoptions
      • Nsjsonreadingmutablecontainers = (1UL << 0)
        • The arrays and dictionaries created are mutable
      • Nsjsonreadingmutableleaves = (1UL << 1)
        • Strings in an array or dictionary are mutable, and iOS7 are invalid later.
      • Nsjsonreadingallowfragments
        • Objects that are allowed to parse are not dictionaries or arrays, such as strings or nsnumber.

OC Object (Foundation object), JSON data (NSData)

+ (NSData *) Datawithjsonobject: (ID) obj options: (nsjsonwritingoptions) opt error: (Nserror *  ) error;

JSON parse address online:

Http://tool.oschina.net/codeformat/json

http://json.parser.online.fr/

Complex JSON data parsing:

    //receive the value of key ID in the dictionary with the ID of the model (need to import Mjextension)[Wsvideos Setupreplacedkeyfrompropertyname:^nsdictionary *{        return@{@"ID":@"ID"};        }]; //1. Create a URLNsurl *url = [Nsurl urlwithstring:@"Http://120.25.226.186:32812/video?type=JSON"]; //2. Create a request based on a URLNsurlrequest *request =[Nsurlrequest Requestwithurl:url]; //3. Send with Nsurlconnection[Nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue Mainqueue] completionHandler:^ ( Nsurlresponse *response, NSData *data, Nserror *connectionerror) {        if(!data)                    {[Self.tableview reloaddata]; }Else{                //parse the JSON data into OC data                IDres =[nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutablecontainers Error:nil]; NSLog (@"%@", RES); if([Res Iskindofclass:[nsarrayclass]]) {NSLog (@"Array"); }Else if([Res iskindofclass:[nsdictionaryclass]]) {NSLog (@"Dict"); //convert OC data into a data model//Save the data model to the model arraySelf.videos = [Wsvideos objectarraywithkeyvaluesarray:res[@"Videos"]]; }                                //Refresh the table (send an asynchronous request, be sure to refresh the table after you get the data)[Self.tableview Reloaddata]; }        }];


(ii) XML data parsing:

The full name is Extensible Markup Language, translated "Extensible Markup Language". Generally also known as XML documents (XML document).

Characteristics:

--

Format:

A common XML document typically consists of the following sections:
1. Document Declaration
2. Elements (Element)
3. Properties (Attribute)

1.XML syntax – Document declaration:

At the very front of the XML document, you must write a document declaration that declares the type of the XML document
The simplest statement
<?xml version= "1.0"?>
Use the Encoding property to describe the character encoding of a document
<?xml version= "1.0" encoding= "UTF-8"?>

2.XML syntax – elements (Element)

An element includes a start tag and an end tag
Elements that have content:<video> yellow </video>
element with no content:<video></video>
No element shorthand for content:<video/>

An element can nest several child elements (no cross-nesting), for example:
<videos>
<video>
<name> Small Yellow No. 01 Department </name>
<length>30</length>
</video>
</videos>

Note: The canonical XML document has a maximum of 1 root elements , and the other elements are descendants of the root element

3.XML syntax – attributes (Attribute)

An element can have multiple properties
<video name= "Little yellow No. 01" length= "/>"
The video element has a name and length two properties
Attribute values must be enclosed in double quotation marks "" or single quotes "

In fact, the information represented by a property can also be represented by a child element, such as
<video>
<name> Despicable Me No. 01 </name>
<length>30</length>
</video>

Note : XML syntax – element of attention

All spaces and line breaks in XML are treated as concrete content
The contents of the following two elements are not the same
1th One
<video> Small yellow people </video>

2nd One
<video>
Minions
</video>

XML Data parsing scheme:

In iOS, XML is parsed in 2 ways, namely sax and Dom parsing.

DOM: Loading an entire XML document into memory at once, which is more suitable for parsing small files
SAX: Starting from the root element, in order to parse an element down, it is more suitable for parsing large files

The analytic means are broadly divided into two types, Apple native/own parser and third-party framework.

First class: Apple native. nsxmlparser,sax method parsing , simple to use

Type II: Third-party frameworks. LIBXML2: pure C language, which is included by default in the iOS SDK while supporting DOM and sax parsing
Gdataxml:dom mode parsing , developed by Google, based on libxml2           

Suggestions for choosing XML parsing methods:
Large files: Nsxmlparser, LIBXML2
Small files:gdataxml, Nsxmlparser, LIBXML2

Because LIBXML2 is a pure C language, it is difficult to use, so it is not recommended. Gdataxml is developed by Google , the analysis is characterized by a one-time upload of the entire XML document into memory, so it is not suitable for large file parsing. In a comprehensive analysis, only Apple's own nsxmlparser is the most commonly used.

Nsxmlparser using (sax parsing):

Characteristics:

Nsxmlparser take is the sax parsing, characterized by event-driven, the following situation will notify the agent
When scanning to the beginning and end of documents (document)
When scanning to the start and end of elements (element)

Steps:

Nsurl *url = [Nsurl urlwithstring:@"Http://120.25.226.186:32812/video?type=XML"]; Nsurlrequest*request =[Nsurlrequest Requestwithurl:url]; [Nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue Mainqueue] CompletionHandler:^ (Nsurlresponse *response, NSData *data, Nserror *connectionerror) {                //1. Create a Nsxmlparser object based on the XML data that needs to be parsedNsxmlparser *parser =[[Nsxmlparser alloc] initwithdata:data]; //2. Set up the agent, through the proxy method to tell Nsxmlparser, which elements and which properties to getParser.Delegate=Self ; //2. Start parsing[parser Parse]; }];

Proxy method:

//whenever you start parsing an XML document, you call- (void) Parserdidstartdocument: (Nsxmlparser *) parser{}//The XML document is called whenever the parsing is complete- (void) Parserdidenddocument: (Nsxmlparser *) parser{//Refresh UI[Self.tableview reloaddata];}//whenever you start parsing an element, you call//elementname: element name//attributedict: Attributes in an element- (void) Parser: (Nsxmlparser *) parser didstartelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI QualifiedName: (NSString *) QName attributes: (nsdictionary *) attributedict{if([ElementName isequaltostring:@"Videos"]) {        return; } Xmgvideo*video =[Xmgvideo objectwithkeyvalues:attributedict]; [Self.videos Addobject:video];}//whenever an element is parsed, it is called- (void) Parser: (Nsxmlparser *) parser didendelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI QualifiedName: (NSString *) qname{}//called when parsing errors occurred- (void) Parser: (Nsxmlparser *) parser validationerroroccurred: (Nserror *) validationerror{NSLog (@"Error");}

Gdataxml using (DOM mode parsing):

Configuration steps:

1. Import the gdataxml Framework, import the LIBXML2 library (IOS8 does not need to import)

2. Set the LIBXML2 header file search path (in order to find all header files for the LIBXML2 library)

Add/USR/INCLUDE/LIBXML2 to head Search path
3. Set link parameters (Auto link libxml2 library)

Add-LXML2 to other Linker flags
4. Because the Gdataxml is non-arc, you have to set the compilation parameters
    

Steps to use:

Classes commonly used in Gdataxml
Gdataxmldocument: Representing the entire XML document

Gdataxmlelement: Represents each element in a document
Use the Attributeforname: method to get the property value

    //1. Create a URLNsurl *url = [Nsurl urlwithstring:@"Http://120.25.226.186:32812/video?type=XML"]; //2. Create requests based on URLNsurlrequest *request =[Nsurlrequest Requestwithurl:url]; //3. Using nsurlconnection to send requests[Nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue Mainqueue] completionHandler:^ ( Nsurlresponse *response, NSData *data, Nserror *connectionerror) {                //1. Create a parserGdataxmldocument *document =[[Gdataxmldocument alloc] Initwithdata:data options:kniloptions Error:nil]; //2. Get the root element of an XML documentGdataxmlelement *rootelement =document.rootelement; //3. Get all child elements under the root elementNsarray *allsubelement = [rootelement elementsforname:@"Video"]; //4. Traverse child elements, take out attributes, convert to model         for(Gdataxmlelement *elementinchallsubelement) {Wsvideos*video =[[Wsvideos alloc] init]; Video.name= [Element Attributeforname:@"name"].stringvalue; Video.id= @ ([element attributeforname:@"ID"].stringvalue.integervalue); Video.length= @ ([element attributeforname:@"length"].stringvalue.integervalue); Video.image= [Element Attributeforname:@"Image"].stringvalue; Video.url= [Element Attributeforname:@"URL"].stringvalue;        [Self.videos Addobject:video]; }        //Refresh Table[Self.tableview Reloaddata]; }];

Comparison of XML and 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: 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.