2012-05-11 103 views
0

用下面的方法...解析JSON文本

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString* path = [documentsDirectory stringByAppendingPathComponent: 
        [NSString stringWithFormat:@"/lkj/"]]; 

NSString *fileName = [NSString stringWithFormat:@"/sandbox/2012_05_11.json"]; 

[[self restClient] loadFile:fileName intoPath:path]; 

NSString *fileContent = [[NSString alloc] initWithContentsOfFile:path]; 

SBJsonParser *parser = [[SBJsonParser alloc] init]; 

NSDictionary *data = (NSDictionary *) [parser objectWithString:fileContent error:nil]; 

// getting the data from inside of "menu" 

NSString *message = (NSString *) [data objectForKey:@"message"]; 
NSString *name = (NSString *) [data objectForKey:@"name"]; 

namegroup.text = [NSString stringWithFormat:@"%@ %@",name, message]; 

...我試圖解析我以前與其他代碼做了一個文件...

{"message":["Untitled1a","Untitled2a","Untitled3a"],"name":["Untitled1b","Untitled2b","Untitled3b"]} 

與雖然上面的代碼,在名稱group.text,這似乎...

(untitled, untitled, untitled) (untitled, untitled, untitled) 

...但我想這樣做是分配許多UITextFields,在對他們每個人,( 2,2,2 ..),其中一個字段顯示名稱,另一個字段顯示消息,因此將1a與1b,2a與2b配對...顯然這些字段不會是Untitled1a,但是「您好嗎」。 ..

但我似乎無法解決這個問題!請幫忙!!

回答

1

您可以嘗試這樣的事:

NSArray *message = [data objectForKey:@"message"]; 
NSArray *name = [data objectForKey:@"name"]; 


NSDictionary* Dictionary = [NSDictionary dictionaryWithObjects:message forKeys:name]; 


for (NSString* Key in [Dictionary allKeys]){ 
    NSLog(@"%@ %@",Key,[Dictionary objectForKey:Key]); 

}