iOS Network data parsing

Source: Internet
Author: User
Tags xml parser

During the development of iOS, the transmission process of network data is usually: the client sends the request to the server, the server receives the network request sent by the client and returns the corresponding data. At this point the client needs to convert the data returned by the server into the data format used in the previous and mobile development (such as Oc/java). Background server is generally used in PHP, Java,. NET development, and the front and mobile use of the general is oc/java/html/css/js, good data interaction between the front and back is extremely important, today data interaction is commonly used in JSON and XML. The following is a simple explanation of JSON parsing and XML parsing during iOS development.

First, JSON parsing

JSON is a lightweight data format that is typically used for data interaction. JSON is a subset of the JavaScript language. JavaScript is a scripting language (no compilation required) to add dynamic functionality to HTML (here JavaScript and Java do not have a half-dime relationship!)

In iOS, there are 4 common JSON data parsing scenarios:

Third-party framework: Sbjson, Jsonkit, Touchjson. Performance from left to right, and in turn, poor. (Before IOS 5 (2011))

Apple native (comes with): Nsjsonserialization (performance is the best. IOS5 later).

The Apple native JSON parsing tool encapsulates the effect is very good, the use is also very convenient, below briefly introduces the JSON parsing method.

<1> deserialization (parsing):

Converts the JSON data (binary data) received from the server to the OC data type (nsarray,nsdictionary, etc.) The process.

Purpose: JSON data----OC object; Get a data dictionary or an array of data

Benefits: Simplify the development of the program, easy to follow the dictionary to model.

Method:

+ (ID) jsonobjectwithdata: (NSData *) Data options: (nsjsonreadingoptions) opt error: (NSERROR *) error;

<2> Serialization:

Converts an array or dictionary to a binary data before sending it to the server.

Purpose: OC Object---JSON data; Get binary JSON data nsdata.

Benefits: Convenient network transmission, improve transmission speed.

Method:

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

It is important to note that before serializing, be sure to use Isvalidjsonobject to detect if the object being serialized is correctly serialized

There is the back of the JSON data back if the error, such as the two sides of the {} or [] did not add, we want to implement through the code, the following list of implementation ideas, not on the code.

Specific ideas: 1. Send a network Request 2. Receive JSON data with a string 3. Standardize the JSON format 4. Converts the normalized JSON string to binary data 5. Convert standard JSON binary data to OC data

Second, parsing XML data

XML full name is Extensible Markup Language, translated "Extensible Markup Language

XML Features:

1, XML is a markup language, very similar to HTML

2, XML is designed to transfer data, not display the data

3. XML tags are not predefined. You need to define your own labels.

4. XML is designed to be self-descriptive.

5, XML is the recommended standard

XML is an information transfer tool that is independent of software and hardware. Currently, the role of XML in the Web does not renmin the HTML that has always been the cornerstone of the Web. XML is ubiquitous. XML is the most common tool for data transfer between applications, and is becoming increasingly popular in the area of information storage and characterization.

Three ways of parsing XML

Dom

Versatile, it reads all the contents of an XML file into memory, and then allows you to use the DOM API to traverse the XML tree and retrieve the data you need;

Simple and intuitive, but need to read the document into memory, not very suitable for mobile devices;

SAX, Pull parsing

Sax is event-driven, and it doesn't need to parse the entire document; Pull (for Java parsing) is an XML parser that comes with Android, basically similar to sax and also event driven, unlike pull events that return numeric types.

The difference is that the SAX parser works by automatically pushing events into the registered event handler, so you can't control the active end of the event's processing, and the pull parser works by allowing your application code to proactively get events from the parser, just because it's actively getting events, Therefore, you can no longer get the event after the desired condition has been satisfied, ending the parsing. This is the main difference between them. If we only need the previous part of the data in an XML document, but use sax or DOM to parse the entire document, the middle cannot terminate the pause, although most of the data later in the XML document we do not need to parse, so this is actually a waste of processing resources. Using the Pull method is appropriate.

Here's an example of XML parsing in iOS development:

//nsxmlparserdelegate//1. Instantiate the SAX parser for XML!Nsxmlparser*parser =[[Nsxmlparser alloc] initwithdata:data]; //2. Set the parser agent.Delegate=Self ; //3. Start parsing XML documents//once the following start parsing method is called, the proxy method is called automatically, parsing the XML document![parser parse];#pragmansxmlparserdelegate-(void) Parserdidstartdocument: (Nsxmlparser *) parser{NSLog (@"1.XML document parsing begins!");}//it will be called when the element is parsed! The number of elements in an XML document is called multiple times!//elementname: element name!//attributedict: Property dictionary! The property dictionary for the current element!- (void) Parser: (Nsxmlparser *) parser didstartelement: (NSString *) elementname NamespaceURI: (Nullable NSString *) NamespaceURI QualifiedName: (Nullable NSString *) QName attributes: (nsdictionary<nsstring *, NSString *> *) attributedict{NSLog (@"2. Start parsing:%@ element, Element attribute is:%@", elementname,attributedict); //judge: Only the element vedio attribute dictionary is required content!     if([ElementName isequaltostring:@"vedio"]) {            //Dictionary Turn ModelCzvideo*video =[Czvideo videowithdict:attributedict]; //add to Data source[Self.videos Addobject:video]; }}//It is called when the element content is found!//string: element content!- (void) Parser: (Nsxmlparser *) parser foundcharacters: (NSString *)string{NSLog (@"3. Element content found:%@",string);}//It is called when the parsing of the element is complete, and how many elements in the XML document are called multiple times!//elementname: element name- (void) Parser: (Nsxmlparser *) parser didendelement: (NSString *) elementname NamespaceURI: (Nullable NSString *) NamespaceURI QualifiedName: (Nullable NSString *) qname{NSLog (@"4. Element%@ parsing End", elementname);}- (void) Parserdidenddocument: (Nsxmlparser *) parser{NSLog (@"5.XML document parsing is over!");}

iOS Network data parsing

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.