[IOS] Plist-XML-JSON data parsing, iosplist-xml-json

Source: Internet
Author: User

[IOS] Plist-XML-JSON data parsing, iosplist-xml-json

Common Data transmitted over the network are XML and JSON, and Plist can also be used in iOS.

To transmit data, you must first serialize the data:

1. serialization. Convert the object to a binary stream. (This sentence is enough.) 2. deserialization. Convert the binary stream to an object. (The key is to clarify this)
JSON: (similar to XML, which is used to transmit data) Lightweight data exchange formats are gradually replacing XML. XML: a structured markup language that is easy to read, but with a large amount of data. PlistPlay occasionally: One more format is used in Mac and iOS.
I. Application scenarios1. XML application scenarios: XMPP-instant messaging, KissXMLRSS currently has a small number of enterprises using open-source WebServices, such as weather forecasts. If XML interfaces are designed, XML parsing is not too complex.
2. JSON application scenarios: (small data size, lightweight) most mobile development uses JSON. If you develop your own data or the company's background interface, it is best to use JSON.
Ii. Plist parsing dataThe format of defining a Plist is as follows:

The parsing code is as follows: (run in asynchronous thread and get array)
-(Void) loadData {// 1. url NSURL * url = [NSURL URLWithString: @ "http: // localhost/videos. plist "]; // 2. request // timeoutInterval If no result is returned from the server within 5.0, it is deemed that the request has timed out/** NSURLRequestUseProtocolCachePolicy = 0, // use the Protocol Cache Policy (default) NSURLRequestReloadIgnoringLocalCacheData = 1, // ignore local cache data (used during resumable upload) NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheData, = 1 // use less than limit = 2, // If cache exists, the cache data is returned, otherwise, load NSURLRequestReturnCacheDataDontLoad = 3. // the remote server data is not loaded. If you do not have a network connection, you can use // The following command to disable callback = 4. // NSURLRequestReloadRevalidatingCacheData = 5, // not implemented */NSURLRequest * request = [NSURLRequest requestWithURL: url cachePolicy: 0 timeoutInterval: 5.0]; // 3. asynchronous Network request [NSURLConnection sendAsynchronousRequest: request queue: [[NSOperationQueue alloc] init] completionHandler: ^ (NSURLResponse * response, NSData * data, NSError * connectionError) {if (connectionError) {NSLog (@ "error % @", connectionError); return;} // data is a plist data that is deserialized to parse NSArray * array = [NSPropertyListSerialization propertyListWithData: data options: 0 format: NULL error: NULL]; // refresh the data and update the UI dispatch_async (dispatch_get_main_queue () in the UI thread (), ^ {//...});}];}

Iii. XML ParsingIn iOS, there are two XML parsing methods (friend pull in Android): 1. SAX (SimpleAPI for XML) can only be read, cannot be modified, and can only be accessed sequentially. It is suitable for parsing large XML files, fast Parsing is often used to process XML with a large amount of data to achieve data access to heterogeneous systems, and cross-platform migration from the beginning of the document through each node, locating a specific node 2 and DOM (writable entobject Model) can not only read but also modify it, but also implement random access. The disadvantage is that the parsing speed is slow and is suitable for parsing small documents. easy to operate. generating node tree in memory is expensive
XML parsing steps: 1. instantiate NSXMLParser and pass in the XML data received from the server. 2. Define the parser proxy. 3. parse the parser. parse the XML data using the parsing proxy method.
The proxy method used to parse XML:

1. Start parsing XML documents

-(Void) parserDidStartDocument:

2. Start parsing an element and traverse the entire XML to identify the element node name,Starting with <video>

-(Void) parser: didStartElement: namespaceURI: qualifiedName: attributes:

3. The text node obtains the information data stored in the text node. Data in the node <video>XXXX</Video>

-(Void) parser: foundCharacters:

4. End a nodeFor example, it starts with </video>.

-(Void) parser: didEndElement: namespaceURI: qualifiedName:

Note: During the parsing process, the 2, 3, and 4 methods will be repeatedly executed until the traversal is complete.

5. parse the XML document.

-(Void) parserDidEndDocument:

6. parsing error

-(Void) parser: parseerroccurred:
Note: adding data from the network cannot be loaded lazily.
The XML file format is as follows::
<? Xml version = "1.0" encoding = "UTF-8"?> <Videos> <video videoId = "1"> <name> instructor Cang 1 </name> <length> 320 </length> <videoURL>/Master 1.mp4 </videoURL> <imageURL >/old teacher 1.png </imageURL> <desc> learn how to find teacher Cang 1 for iOS </desc> <teacher> instructor Cang 111 </teacher> </video> <video videoId = "2 "> <name> instructor Cang 2 </name> <length> 2708 </length> <videoURL>/instructor 2.mp4 </videoURL> <imageURL>/instructor 2.png </imageURL> <desc> learn about iOS and find teacher Cang 2 </desc> <teacher> instructor Cang 222 </teacher> </video> </videos>
The parsing code is as follows::
/** Load data */-(void) loadData {// 1. url determine resource NSURL * url = [NSURL URLWithString: @ "http: // localhost/videos. xml "]; // 2. request NSURLRequest * request = [NSURLRequest requestWithURL: url]; // 3. send an asynchronous request to create a data processing queue. After the data processing is complete, update the UI [NSURLConnection sendAsynchronousRequest: request queue: [[NSOperationQueue alloc] init] completionHandler: ^ (NSURLResponse * response, NSData * data, NSError * connectionError ){// 1> instantiate the XML parser NSXMLParser * parser = [[NSXMLParser alloc] initWithData: data]; // 2> set the parser's proxy parser. delegate = self; // 3> Start parsing [parser parse] ;}] ;## pragma mark-XML parsing proxy method // 1. start parsing the document-(void) parserDidStartDocument :( NSXMLParser *) parser {// to avoid repeated data refresh, you can clear the array [self. videoList removeAllObjects];} // 3, 4 three methods will be called cyclically // 2. start an element (node) <xxx>-(void) parser :( NSXMLParser *) parser didStartElement :( NSString *) elem EntName namespaceURI :( NSString *) namespaceURI qualifiedName :( NSString *) qName attributes :( NSDictionary *) attributeDict {if ([elementName isEqualToString: @ "video"]) {// create a new video object self. currentVideo = [[Video alloc] init]; // assign a value to [self. currentVideo setValue: attributeDict [@ "videoId"] forKeyPath: @ "videoId"];} // clear the string content [self. elementM setString: @ ""];} // 3. detected characters (intermediate content of the node)-(void) parser :( NSXMLParser *) parser foundCharacters :( NSString *) string {[self. elementM appendString: string];} // 4. end node </xxx>-(void) parser :( NSXMLParser *) parser didEndElement :( NSString *) elementName namespaceURI :( NSString *) namespaceURI qualifiedName :( NSString *) qName {if ([elementName isinclutostring: @ "video"]) {// Add the node currently being parsed to the array [self. videoList addObject: self. currentVideo];} else if (! [ElementName isEqualToString: @ "videos"]) {[self. currentVideo setValue: self. elementM forKeyPath: elementName] ;}// 5. end document parsing-(void) parserDidEndDocument :( NSXMLParser *) parser {NSLog (@ "end document parsing % @", self. videoList); NSLog (@ "% @", [NSThread currentThread]); dispatch_async (dispatch_get_main_queue (), ^ {// refresh the UI...} in the UI thread ......});} // 6. do not forget to handle errors when processing network data-(void) parser :( NSXMLParser *) parser parseerroccurred :( NSError *) parseError {NSLog (@ "error % @", parseError );}

Iv. JSON ParsingThe parsed data needs to be deserialized as follows: [NSJSONSerialization JSONObjectWithData: Data options: 0 error: NULL];
JSON Parsing is convenient and lightweight, especially for mobile phones, which saves traffic and is fast. JSON format data is as follows:
[{"VideoId": "1", "name": "instructor Cang 1", "length": "320", "videoURL": "\/instructor 1.mp4 ", "imageURL": "\/old teacher 1.png", "desc": "Learn iOS to find teacher Cang 1", "teacher": "miss Cang 111" },{ "videoId ": "2", "name": "instructor Cang 2", "length": "2708", "videoURL": "\/instructor 2.mp4", "imageURL ": "\/old teacher 2.png", "desc": "Learn iOS to find teacher Cang 2", "teacher": "miss Cang 222"}]
The parsing code is as follows:
-(Void) loadData {// 1. url NSURL * url = [NSURL URLWithString: @ "http: // localhost/videos. json "]; // 2. request NSURLRequest * request = [NSURLRequest requestWithURL: url]; // 3. send an asynchronous request [NSURLConnection sendAsynchronousRequest: request queue: [[NSOperationQueue alloc] init] completionHandler: ^ (NSURLResponse * response, NSData * data, NSError * connectionError) {// data is a json data // deserialization of data, parsing NSArray * array = [NSJSONSerialization JSONObjectWithData: data options: 0 error: NULL]; // refresh data, update UI dispatch_async (dispatch_get_main_queue (), ^ {// update UI...} in the main thread);}];}


Reprinted please indicate the source: http://blog.csdn.net/xn4545945




For ios developers, refer to plist file parsing.

The plist file is equivalent to the dictionay file in the program, which can be nested with dictionary or array layers. Resolution is to read the content and put it into dictionary.

How to parse xml data from ios asihttprequest

Use the most basic keyword search or some XML parsing frameworks.
Like the NSXMLParser that comes with the sdk
Or google's NSData

NSXMLParse is directly searched in the document for sample code and documentation help
NSData google or baidu search, many examples on the Internet

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.