Introduction to the Objective C method for parsing XML and JSON data formats

  • 2020-05-14 04:53:07
  • OfStack

Parsing XML
This article takes parsing local XML as an example. The return value obtained by the network only needs to be converted to NSData type, and the parsing is the same

The xml files that need to be parsed are as follows, users.xml


<?xml version="1.0" encoding="UTF-8"?>
<AllUsers>
 <message> The user information </message>
 <user>
  <name> Fang zai small footprint </name>
  <age>10</age>
  <school>JiangSu University</school>
 </user>
 <user>
  <name> The vermin </name>
  <age>22</age>
  <school>NanJing University</school>
 </user>
 <user>
  <name> The goddess </name>
  <age>23</age>
  <school>HongKong University</school>
 </user>
</AllUsers>

We use 1 array to store, and the final data structure is


(
    {
    message = " The user information ";
  },
    {
    age = 10;
    name = " Fang zai small footprint ";
    school = "JiangSu University";
  },
    {
    age = 22;
    name = " The vermin ";
    school = "NanJing University";
  },
    {
    age = 23;
    name = " The goddess ";
    school = "HongKong University";
  }
)

Analytical steps

1. Declare NSXMLParserDelegate

2.


// In the node message and user as 1 Three dictionaries
    NSArray *keyElements = [[NSArray alloc] initWithObjects:@"message",@"user", nil];
    // The fields that need to be parsed
    NSArray *rootElements = [[NSArray alloc] initWithObjects:@"message",@"name",@"age",@"school", nil];
    // To obtain xml Path to file
    NSString *xmlPath = [[NSBundle mainBundle] pathForResource:@"users" ofType:@"xml"];
    // into Data
    NSData *data = [[NSData alloc] initWithContentsOfFile:xmlPath];
    
    // Initialize the
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];
    
    // The agent
    xmlParser.delegate = self;
    // Start parsing
    BOOL flag = [xmlParser parse];
    if (flag) {
        NSLog(@" Parsing the success ");
    }
    else{
        NSLog(@" Parse error ");
    }

Intermediate variable, defined in interface of.m

NSString *currentElement;
    
    NSString *currentValue;
    
    NSMutableDictionary *rootDic;
    
    NSMutableArray *finalArray;

Proxy method

#pragma - mark At the beginning of parsing
-(void)parserDidStartDocument:(NSXMLParser *)parser
{
    // Store each in an array 1 Group information
    finalArray = [[NSMutableArray alloc] init];
    
    
}
#pragma - mark Node discovery
-(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]) {
            // When the critical node starts, it is initialized 1 A dictionary to hold the values
            rootDic = nil;
            
            rootDic = [[NSMutableDictionary alloc] initWithCapacity:0];
            
        }
        else {
            for(NSString *element in self.rootElements){
                if ([element isEqualToString:element]) {
                    currentElement = elementName;
                    currentValue = [NSString string];
                }
            }
        }
    }
    
}
#pragma - mark When a node value is found
 
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    
    if (currentElement) {
 
        currentValue = string;
        [rootDic setObject:string forKey:currentElement];
    }
    
}
#pragma - mark End of 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 the array
            if (rootDic) {
 
                [finalArray addObject:rootDic];
            }
        }
    }
}
#pragma - mark The end of the parse
-(void)parserDidEndDocument:(NSXMLParser *)parser
{
    
}

Once parsing is complete, print out finalArray as


(
 {
  message = "\U7528\U6237\U4fe1\U606f";
 },
 {
  age = 10;
  name = "\U82b3\U4ed4\U5c0f\U811a\U5370";
  school = "JiangSu University";
 },
 {
  age = 22;
  name = "\U6bd2\U866b";
  school = "NanJing University";
 },
 {
  age = 23;
  name = "\U5973\U795e";
  school = "HongKong University";
 }
)

Use SBJson to splice and parse json
1. The analytical json ios
Use the open source json package, project address:
http://www.superloopy.io/json-framework/


NSData * responseData = [respones responseData];
     
     NSString * strResponser = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
SBJsonParser * parser = [[SBJsonParser alloc]init];
     NSMutableDictionary *dicMessageInfo = [parser objectWithString:strResponser]; // Parsed into json Analytical object
[parser release];
     // The sender
     NSString * sender = [dicMessageInfo objectForKey:@"sender"];

2.json nested object resolution:

// The string to upload
    NSString *dataStr=[[NSString alloc] initWithString:@"{\"cross\":{\"1\":\"true\",\"2\":\"false\",\"3\":\"true\"}}"];
// Gets the response return string
NSData * responseData = [respones responseData];
       
        NSString * strResponser = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// Nested parsing
SBJsonParser * parser = [[SBJsonParser alloc]init];
           
            NSMutableDictionary *dicMessageInfo = [parser objectWithString:strResponser]; // Parsed into json Analytical object
           
            NSMutableDictionary * cross = [dicMessageInfo objectForKey:@"cross"];
           
            NSString *cross1= [cross objectForKey:@"1"];
            // parsing json To the individual strings
            // The sender
            [parser release];
            NSLog(@"cross1: %@",cross1);

3. Concatenate json string

By using the SBJsonWriter class method - (NSString*)stringWithObject (id)value, the value of an object can be formatted into an json string. Data in key/value format can be formatted using this method after being encapsulated into NSDictionary. Other data can be formatted by concatenating strings.
You can use the NSMutableString method during the splicing process:

 
- (void)appendString:(NSString *)aString; ,
- (void)appendFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);

Dynamically add a string.
The concatenated string can be verified to be in the correct format by json online verification at:
http://jsonlint.com/

-(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 to concatenate multi-layer nested json strings to reduce errors in json format caused by manual concatenation forgetting to put quotation marks
Sample code:

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