概要Objective-C XMLとJSONデータフォーマットを解析する方法

9812 ワード

解析XML本稿では,ローカルXMLの解析を例にとると,ネットワークが取得した戻り値をNSData型に変換するだけで,解析は同様である.
解析するxmlファイルは次のとおりです.xml



     
 
       
  10
  JiangSu University
 
 
    
  22
  NanJing University
 
 
    
  23
  HongKong University
 


最終的なデータ構造は

(
    {
    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にカプセル化した後、このメソッドを使用してフォーマットできます.その他の数値は文字列をつなぎ合わせることでフォーマットできます.パッチ処理中にクラスNSMutablesStringの方法を使用できます.
 
  
- (void)appendString:(NSString *)aString;、
- (void)appendFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);

文字列を動的に追加します.
接続された文字列は、jsonがオンラインで検証した方法でフォーマットが正しいかどうかを検証できます.URLは次のとおりです.
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);