欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2023-11-18 13:48:34
解析xml 本文以解析本地xml为例,网络获取到的返回值只需转换成nsdata型,解析是同理 需要解析的xml文件如下,users.xml

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