Introduction to OBJECTIVE-C parsing XML and JSON data formats _ios

Source: Internet
Author: User
Tags parse error

Parsing xml
in this paper, for example, to parse local XML, the return value obtained by the network can only be converted into NSData type, and parsing is the same

The XML file that needs to be parsed is as follows, Users.xml

<?xml version= "1.0" encoding= "UTF-8"?>
<AllUsers>
 <message> user Information </message>
 <user>
  <name> Fang Xiao Footprint </name>
  <age>10</age>
  <school>jiangsu university</school>
 </user>
 <user>
  <name> Junkie </name>
  <age> 22</age>
  <school>nanjing university</school>
 </user>
 <user>
  <name> Goddess </name>
  <age>23</age>
  <school>hongkong university</school >
 </user>
</AllUsers>

We use an array to store the final data structure as

(
    {
    message = "user Information";
  },
    {age
    = ten;
    Name = "Small footprint of Fang Zi";
    School = "Jiangsu University";
  },
    {age
    =;
    Name = "poisonous insect";
    School = "Nanjing University";
  },
    {age
    = n;
    Name = "Goddess";
    School = "Hongkong University";
  }
)

Parsing steps

I. Declaration OF Agent Nsxmlparserdelegate

Second, analysis

Copy Code code as follows:

Store as a dictionary when node message and user are encountered
Nsarray *keyelements = [[Nsarray alloc] initwithobjects:@ "message", @ "user", nil];
Fields that need to be resolved
Nsarray *rootelements = [[Nsarray alloc] initwithobjects:@ ' message ', @ ' name ', @ ' age ', @ ' school ', nil];
Get path to XML file
NSString *xmlpath = [[NSBundle mainbundle] pathforresource:@ "Users" oftype:@ "xml"];
Converted to data
NSData *data = [[NSData alloc] initwithcontentsoffile:xmlpath];

Class
Nsxmlparser *xmlparser = [[Nsxmlparser alloc] initwithdata:data];

Agent
Xmlparser.delegate = self;
Start parsing
BOOL flag = [Xmlparser parse];
if (flag) {
NSLog (@ "parse success");
}
else{
NSLog (@ "Parse error");
}

Intermediate variables, defined in the interface of. m
Copy Code code as follows:

NSString *currentelement;

NSString *currentvalue;

Nsmutabledictionary *rootdic;

Nsmutablearray *finalarray;

Proxy method
Copy Code code as follows:

#pragma-mark begins parsing
-(void) Parserdidstartdocument: (Nsxmlparser *) parser
{
Storing each set of information in an array
Finalarray = [[Nsmutablearray alloc] init];


}
When a node is found #pragma-mark
-(void) Parser: (Nsxmlparser *) parser didstartelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI QualifiedName: (NSString *) QName attributes: (nsdictionary *) attributedict
{
For (NSString *key in self.keyelements) {
if ([elementname Isequaltostring:key]) {
Initializes a dictionary to hold the value at the beginning of the critical node
Rootdic = nil;

Rootdic = [[Nsmutabledictionary alloc] initwithcapacity:0];

}
else {
For (NSString *element in self.rootelements) {
if ([element isequaltostring:element]) {
Currentelement = elementname;
CurrentValue = [NSString string];
}
}
}
}

}
When a node value is found #pragma-mark

-(void) Parser: (Nsxmlparser *) parser foundcharacters: (NSString *) string
{

if (currentelement) {

CurrentValue = string;
[Rootdic setobject:string forkey:currentelement];
}

}
#pragma-mark End Node
-(void) Parser: (Nsxmlparser *) parser didendelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI QualifiedName: (NSString *) qName
{
if (currentelement) {
[Rootdic Setobject:currentvalue forkey:currentelement];
Currentelement = nil;
CurrentValue = nil;
}
For (NSString *key in self.keyelements) {

if ([elementname Isequaltostring:key]) {
When the key node ends, the dictionary is stored in an array
if (rootdic) {

[Finalarray Addobject:rootdic];
}
}
}
}
#pragma-mark End resolution
-(void) Parserdidenddocument: (Nsxmlparser *) parser
{

}

After parsing is complete, print out Finalarray as

(
 {Message
  = ' \u7528\u6237\u4fe1\u606f ';
 },
 {age
  = ten;
  Name = "\u82b3\u4ed4\u5c0f\u811a\u5370";
  School = "Jiangsu University";
 },
 {age
  =;
  Name = "\u6bd2\u866b";
  School = "Nanjing University";
 },
 {age
  = n;
  Name = "\U5973\U795E";
  School = "Hongkong University";
 }
)

Using Sbjson stitching and parsing json
1.ios parsing JSON
using Open source JSON package, project address:
http://www.superloopy.io/json-framework/

Copy Code code as follows:

NSData * ResponseData = [Respones responsedata];

NSString * Strresponser = [[NSString alloc] Initwithdata:responsedata encoding:nsutf8stringencoding];
Sbjsonparser * parser = [[Sbjsonparser alloc]init];
Nsmutabledictionary *dicmessageinfo = [parser objectwithstring:strresponser]; Parse into JSON parse object
[Parser release];
Sent by
NSString * sender = [dicmessageinfo objectforkey:@ "Sender"];

2.json Nested object resolution:
Copy Code code as follows:

The string to upload
NSString *datastr=[[nsstring Alloc] initwithstring:@ "{\ cross\": {\ "1\": \ "true\", \ "2\": \ "false\", \ "3\": \ "true\"} " ];
Get response return string
NSData * ResponseData = [Respones responsedata];

NSString * Strresponser = [[NSString alloc] Initwithdata:responsedata encoding:nsutf8stringencoding];
Nesting parsing
Sbjsonparser * parser = [[Sbjsonparser alloc]init];

Nsmutabledictionary *dicmessageinfo = [parser objectwithstring:strresponser]; Parse into JSON parse object

Nsmutabledictionary * Cross = [Dicmessageinfo objectforkey:@ "Cross"];

NSString *cross1= [Cross objectforkey:@ "1"];
Parse JSON to individual strings
Sent by
[Parser release];
NSLog (@ "Cross1:%@", CROSS1);

3. Splicing JSON strings

By using the Sbjsonwriter class in Sbjson-(nsstring*) Stringwithobject: (ID) value can format the value in one object as a JSON string, in accordance with the key/ Data in the value format can be formatted using this method after being encapsulated into nsdictionary, and other data is formatted by stitching strings.
You can use the method of class nsmutablestring in the stitching process:

Copy Code code as follows:

-(void) appendstring: (NSString *) astring;
-(void) AppendFormat: (NSString *) format, ... Ns_format_function (1,2);

Adds a string dynamically.
The concatenation of the strings can be verified by JSON online validation of the correct format, the URL is:
http://jsonlint.com/
Copy Code code as follows:

-(NSString *) getjsonstring
{
nsmutablestring *json = [nsmutablestring stringwithcapacity:128];
NSString *jsonstring=nil;
Sbjsonwriter *writer = [[Sbjsonwriter alloc] init];
[JSON appendstring:@ ' {\ ' data\ ': {];
[JSON appendformat:@ "\%@\": \ "%d\", "," "Reset", reset];
if (missionstatus!=null)
{
Jsonstring=[writer Stringwithobject:status];
if (jsonstring!=null)
{
[JSON appendstring:@ "\" status\ ":"];
[JSON appendstring:jsonstring];
}
}
[JSON appendstring:@ '}} '];
return JSON;
}

4. Use multiple nsdictionary, splicing multilayer nested JSON string, reduce the JSON format error caused by manual stitching forgotten Quotes
Sample code:
Copy Code code as follows:

Nsdictionary *datadictionary= [nsdictionary dictionarywithobjectsandkeys:mac,@ "Mac",
game,@ "Game",
devicetoken,@ "Devicetoken",
device,@ "Device",
gv,@ "GV",
lang,@ "Lang",
os,@ "OS",
hardware,@ "Hardware",
down,@ "Down", nil];
Nsdictionary *parmdictionary= [nsdictionary dictionarywithobjectsandkeys:@ "getsession", @ "Act",
datadictionary,@ "Data", nil];
Nsdictionary *jsondictionary=[nsdictionary dictionarywithobjectsandkeys:pv,@ "PV",
parmdictionary,@ "Param", nil];
Sbjsonwriter *writer = [[Sbjsonwriter alloc] init];

NSString *jsonstring=nil;
Jsonstring=[writer Stringwithobject:jsondictionary];
NSLog (@ "%@", jsonstring);

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.