SoFunction
Updated on 2025-04-06

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

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

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

<?xml version="1.0" encoding="UTF-8"?>
<AllUsers>
 <message>User Information</message>
 <user>
  <name>Fangzi's footprints</name>
  <age>10</age>
  <school>JiangSu University</school>
 </user>
 <user>
  <name>poisonous insect</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

(
    {
    message = "User Information";
  },
    {
    age = 10;
    name = "Fangzi's little footprints";
    school = "JiangSu University";
  },
    {
    age = 22;
    name = "poisonous insect";
    school = "NanJing University";
  },
    {
    age = 23;
    name = "goddess";
    school = "HongKong University";
  }
)

Analysis steps

1. Declare agent NSXMLParserDelegate

2. Analysis

Copy the codeThe code is as follows:

// When encountering node message and user, it is stored as a dictionary
    NSArray *keyElements = [[NSArray alloc] initWithObjects:@"message",@"user", nil];
// Fields that need to be parsed
    NSArray *rootElements = [[NSArray alloc] initWithObjects:@"message",@"name",@"age",@"school", nil];
// Get the path to the xml file
    NSString *xmlPath = [[NSBundle mainBundle] pathForResource:@"users" ofType:@"xml"];
// Convert to Data
    NSData *data = [[NSData alloc] initWithContentsOfFile:xmlPath];
    
// Initialization
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];
    
// acting
    = self;
// Start parsing
    BOOL flag = [xmlParser parse];
    if (flag) {
NSLog(@"Resolution successful");
    }
    else{
NSLog(@"Resolution error");
    }

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

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

Proxy method
Copy the codeThe code is as follows:

#pragma - mark When parsing
-(void)parserDidStartDocument:(NSXMLParser *)parser
{
// Use arrays to store each set of information
    finalArray = [[NSMutableArray alloc] init];
    
    
}
#pragma - mark When discovering nodes
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    for(NSString *key in ){
        if ([elementName isEqualToString:key]) {
// When the key node starts, an initial dictionary is initialized to store the value
            rootDic = nil;
            
            rootDic = [[NSMutableDictionary alloc] initWithCapacity:0];
            
        }
        else {
            for(NSString *element in ){
                if ([element isEqualToString:element]) {
                    currentElement = elementName;
                    currentValue = [NSString string];
                }
            }
        }
    }
    
}
#pragma - mark When node value is discovered
 
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    
    if (currentElement) {
 
        currentValue = string;
        [rootDic setObject:string forKey:currentElement];
    }
    
}
#pragma - mark ends 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 ){
 
        if ([elementName isEqualToString:key]) {
// When the key node ends, store the dictionary in the array
            if (rootDic) {
 
                [finalArray addObject:rootDic];
            }
        }
    }
}
#pragma - mark end analysis
-(void)parserDidEndDocument:(NSXMLParser *)parser
{
    
}

After the parsing is completed, print out the 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
Parse json
Use open source json package, project address:
/json-framework/

Copy the codeThe code is 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 parsing object
[parser release];
//Sender
     NSString * sender = [dicMessageInfo objectForKey:@"sender"];

Nested object parsing:
Copy the codeThe code is as follows:

//The string to upload
    NSString *dataStr=[[NSString alloc] initWithString:@"{\"cross\":{\"1\":\"true\",\"2\":\"false\",\"3\":\"true\"}}"];
//Get the response to return the 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]; // parse into json parsing object
           
            NSMutableDictionary * cross = [dicMessageInfo objectForKey:@"cross"];
           
            NSString *cross1= [cross objectForKey:@"1"];
//Parse json to various strings
//Sender
            [parser release];
            NSLog(@"cross1: %@",cross1);

3. Splicing json strings

By using the method of the SBJsonWriter class in SBJson - (NSString*)stringWithObject:(id)value, the value in an object can be formatted as a json string. After data in accordance with the key/value format is encapsulated into NSDictionary, this method can be used for formatting, and other data is formatted by splicing strings.
During the splicing process, you can use the method class NSMutableString:

Copy the codeThe code is as follows:

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

Add string dynamically.
The spliced ​​string can be verified by JSON online verification. The URL is:
/
Copy the codeThe code is 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 to splice multi-layer nested json strings to reduce json format errors caused by forgetting to add quotes by hand splicing
Sample code:
Copy the codeThe code is 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);