简介Objective-C解析XML与JSON数据格式的方法

这篇文章主要介绍了Objective-C解析XML与JSON数据格式的方法,文中解析JSON包括拼接JSON字符串用到了SBJson这个解析器,需要的朋友可以参考下

解析XML
本文以解析本地XML为例,网络获取到的返回值只需转换成NSData型,解析是同理

需要解析的xml文件如下,users.xml


<?xml version="1.0" encoding="UTF-8"?>
<AllUsers>
 <message>用户信息</message>
 <user>
  <name>芳仔小脚印</name>
  <age>10</age>
  <school>JiangSu University</school>
 </user>
 <user>
  <name>毒虫</name>
  <age>22</age>
  <school>NanJing University</school>
 </user>
 <user>
  <name>女神</name>
  <age>23</age>
  <school>HongKong University</school>
 </user>
</AllUsers>

我们用一个数组来存放,最终数据结构为


(
    {
    message = "用户信息";
  },
    {
    age = 10;
    name = "芳仔小脚印";
    school = "JiangSu University";
  },
    {
    age = 22;
    name = "毒虫";
    school = "NanJing University";
  },
    {
    age = 23;
    name = "女神";
    school = "HongKong University";
  }
)

解析步骤

一、声明代理 NSXMLParserDelegate

二、解析

代码如下:

// 遇到节点message和user时作为一个字典存放
    NSArray *keyElements = [[NSArray alloc] initWithObjects:@"message",@"user", nil];
    // 需要解析的字段
    NSArray *rootElements = [[NSArray alloc] initWithObjects:@"message",@"name",@"age",@"school", nil];
    // 获取xml文件的路径
    NSString *xmlPath = [[NSBundle mainBundle] pathForResource:@"users" ofType:@"xml"];
    // 转化为Data
    NSData *data = [[NSData alloc] initWithContentsOfFile:xmlPath];
    
    // 初始化
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];
    
    // 代理
    xmlParser.delegate = self;
    // 开始解析
    BOOL flag = [xmlParser parse];
    if (flag) {
        NSLog(@"解析成功");
    }
    else{
        NSLog(@"解析出错");
    }

中间变量,在.m的interface的中定义
代码如下:

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

代理方法
代码如下:

#pragma - mark 开始解析时
-(void)parserDidStartDocument:(NSXMLParser *)parser
{
    // 用数组存储每一组信息
    finalArray = [[NSMutableArray alloc] init];
    
    
}
#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]) {
            // 关键节点开始时,初始化一个字典来存放值
            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 发现节点值时
 
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    
    if (currentElement) {
 
        currentValue = string;
        [rootDic setObject:string forKey:currentElement];
    }
    
}
#pragma - mark 结束节点时
-(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]) {
            // 关键节点结束时,将字典存放在数组中
            if (rootDic) {
 
                [finalArray addObject:rootDic];
            }
        }
    }
}
#pragma - mark 结束解析
-(void)parserDidEndDocument:(NSXMLParser *)parser
{
    
}

解析完成后,打印出finalArray为


(
 {
  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";
 }
)

使用SBJson拼接和解析json
1.ios解析json
使用开源json包,项目地址:
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]; // 解析成json解析对象
[parser release];
     //发送者
     NSString * sender = [dicMessageInfo objectForKey:@"sender"];

2.json嵌套对象解析:
代码如下:

//要上传的字符串
    NSString *dataStr=[[NSString alloc] initWithString:@"{\"cross\":{\"1\":\"true\",\"2\":\"false\",\"3\":\"true\"}}"];
//获取响应返回字符串
NSData * responseData = [respones responseData];
       
        NSString * strResponser = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
//嵌套解析
SBJsonParser * parser = [[SBJsonParser alloc]init];
           
            NSMutableDictionary *dicMessageInfo = [parser objectWithString:strResponser]; // 解析成json解析对象
           
            NSMutableDictionary * cross = [dicMessageInfo objectForKey:@"cross"];
           
            NSString *cross1= [cross objectForKey:@"1"];
            //解析json到各个字符串
            //发送者
            [parser release];
            NSLog(@"cross1: %@",cross1);

3.拼接json字符串

通过使用SBJson中的SBJsonWriter类的方法- (NSString*)stringWithObject:(id)value可以将一个对象中的值格式化为json字符串,符合key/value格式的数据封装到NSDictionary后可以使用该方法进行格式化,其他数据通过拼接字符串的方式格式化。
在拼接过程中可以使用类NSMutableString的方法:

代码如下:

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

动态添加字符串。
拼接的字符串可通过json在线验证的方式验证其格式是否正确,网址为:
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.利用多个NSDictionary,拼接多层嵌套的json字符串,减少因手工拼接忘记加引号导致的json格式错误
示例代码:
代码如下:

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);

本文标题为:简介Objective-C解析XML与JSON数据格式的方法

基础教程推荐