你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> 簡介Objective-C解析XML與JSON數據格局的辦法

簡介Objective-C解析XML與JSON數據格局的辦法

編輯:IOS開發綜合

解析XmlRss/ target=_blank class=infotextkey>Xml
本文以解析當地XmlRss/ target=_blank class=infotextkey>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";
  }
)

解析步調

1、聲明朝理 NSXMLParserDelegate

2、解析

// 碰到節點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數據格局的辦法】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved