當一個系統(tǒng)與多個外部系統(tǒng)對接時,在請求接口的響應(yīng)中經(jīng)常會遇到異構(gòu)數(shù)據(jù),這個時候它可以返回XML,下面是武林技術(shù)頻道小編為大家解析XML與JSON數(shù)據(jù)格式的方法,一起來了解一下吧!
解析XML
本文以解析本地XML為例,網(wǎng)絡(luò)獲取到的返回值只需轉(zhuǎn)換成NSData型,解析是同理
需要解析的xml文件如下,users.xml
<?xml version="1.0" encoding="UTF-8"?>用戶信息芳仔小腳印10JiangSu University毒蟲22NanJing University女神23HongKong University
我們用一個數(shù)組來存放,最終數(shù)據(jù)結(jié)構(gòu)為
( { message = "用戶信息"; }, { age = 10; name = "芳仔小腳印"; school = "JiangSu University"; }, { age = 22; name = "毒蟲"; school = "NanJing University"; }, { age = 23; name = "女神"; school = "HongKong University"; })解析步驟
一、聲明代理 NSXMLParserDelegate
二、解析
復(fù)制代碼 代碼如下:
// 遇到節(jié)點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"];
??? // 轉(zhuǎn)化為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的中定義
?
復(fù)制代碼 代碼如下:
?
NSString *currentElement;
????
??? NSString *currentValue;
????
??? NSMutableDictionary *rootDic;
????
??? NSMutableArray *finalArray;
代理方法
?
復(fù)制代碼 代碼如下:
?
#pragma - mark 開始解析時
-(void)parserDidStartDocument:(NSXMLParser *)parser
{
??? // 用數(shù)組存儲每一組信息
??? finalArray = [[NSMutableArray alloc] init];
????
????
}
#pragma - mark 發(fā)現(xiàn)節(jié)點時
-(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]) {
??????????? // 關(guān)鍵節(jié)點開始時,初始化一個字典來存放值
??????????? 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 發(fā)現(xiàn)節(jié)點值時
?
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
????
??? if (currentElement) {
?
??????? currentValue = string;
??????? [rootDic setObject:string forKey:currentElement];
??? }
????
}
#pragma - mark 結(jié)束節(jié)點時
-(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]) {
??????????? // 關(guān)鍵節(jié)點結(jié)束時,將字典存放在數(shù)組中
??????????? if (rootDic) {
?
??????????????? [finalArray addObject:rootDic];
??????????? }
??????? }
??? }
}
#pragma - mark 結(jié)束解析
-(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/
復(fù)制代碼 代碼如下:
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];
???? //發(fā)送者
???? NSString * sender = [dicMessageInfo objectForKey:@"sender"];
2.json嵌套對象解析:
?
復(fù)制代碼 代碼如下:
?
//要上傳的字符串
??? NSString *dataStr=[[NSString alloc] initWithString:@"{/"cross/":{/"1/":/"true/",/"2/":/"false/",/"3/":/"true/"}}"];
//獲取響應(yīng)返回字符串
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到各個字符串
??????????? //發(fā)送者
??????????? [parser release];
??????????? NSLog(@"cross1: %@",cross1);
3.拼接json字符串
?
通過使用SBJson中的SBJsonWriter類的方法- (NSString*)stringWithObject:(id)value可以將一個對象中的值格式化為json字符串,符合key/value格式的數(shù)據(jù)封裝到NSDictionary后可以使用該方法進行格式化,其他數(shù)據(jù)通過拼接字符串的方式格式化。
在拼接過程中可以使用類NSMutableString的方法:
復(fù)制代碼 代碼如下:
- (void)appendString:(NSString *)aString;、
- (void)appendFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
動態(tài)添加字符串。
拼接的字符串可通過json在線驗證的方式驗證其格式是否正確,網(wǎng)址為:
http://jsonlint.com/
?
復(fù)制代碼 代碼如下:
?
-(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字符串,減少因手工拼接忘記加引號導(dǎo)致的json格式錯誤
示例代碼:
?
復(fù)制代碼 代碼如下:
?
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);
以上就是解析XML與JSON數(shù)據(jù)格式的方法,更多介紹請繼續(xù)關(guān)注武林技術(shù)頻道!
?