如何解析Json对象

时间:2012-10-08 05:17:29

标签: iphone objective-c ios xcode json

我坚持json对象解析真的很努力。问题是如何解析json对象。这是我在日志中得到的答案。

{"0":{"**title**":"Test Event","url_title":"test_event1","status":"open","entry_date":"Sep 10, 2012, 

05:20:38AM","entry_id":"26","site_id":"1","channel_id":"3","field_dt_40":null,"field_dt_58":null,"channel_title":"News & 

Events","channel_name":"news_events","start_date":"1348120800","end_date":"1348120800","start_time": "43200","end_time":"46800","where":"FCF","news_event_description":"<p>\n\tLunch with group.<\/p>\n"},

"1":{"**title**":"Test Event 2","url_title":"test_event_2","status":"open","entry_date":"Sep 10, 2012, 05:20:08AM","entry_id":"28","site_id":"1","channel_id":"3","field_dt_40":null,"field_dt_58":null,"channel_title":"News & Events","channel_name":"news_events","start_date":"1348207200","end_date":"1348207200","start_time":"43200","end_time":"46800","where":"FCF - Lunch","news_event_description":"<p>\n\tThis was a great event.<\/p>\n"},

"2":{"**title**":"Test Event 3","url_title":"test_event_3","status":"open","entry_date":"Sep 10, 2012, 05:20:54AM","entry_id":"29","site_id":"1","channel_id":"3","field_dt_40":null,"field_dt_58":null,"channel_title":"News & Events","channel_name":"news_events","start_date":"1346738400","end_date":"1346738400","start_time":"7200","end_time":"11700","where":"FCF - Lunch","news_event_description":"<p>\n\tFall planning season.<\/p>\n"}}

问题是我想在tableview中显示所有标题。我可以使用键0,1,2获得单个标题。但我希望我解析所有标题立即显示

请帮帮我们,先谢谢。

2 个答案:

答案 0 :(得分:3)

假设jsonDict是你的json字典....试试这个

NSArray * keys=[[NSArray alloc]init];
keys=[jsonDict allKeys];
NSMutableArray *titles=[[NSMutableArray alloc]init];
for(int i=0;i<[keys count];i++){
      [titles addObject:[[jsonDict valueForKey:[keys objectAtIndex:i]]valueForKey:@"title"]];
}
NSLog(@"your array of titles : %@",titles); //use this array to fill your cell

答案 1 :(得分:2)

您是否尝试自己解析JSON?您可能会发现使用经过良好测试的内容更容易,例如TouchJSON或Apple自己的NSJSONSerilization。结果应该是您可以使用的Objective-C对象图。

无论如何,你所拥有的是相当于词典的词典。如果您将其作为名为myJSONDictionary的NSDictionary,您可以说:

NSArray *theObjects = [myJSONDictionary allValues]; // gets all the objects
NSArray *theTitles = [theObjects valueForKey:@"**title**"]; // gets all the titles

您还可以使用快速枚举迭代字典:

NSMutableArray *theTitles = [NSMutableArray array];
for (NSString *key in myJSONDictionary) {
    NSDictionary *object = [myJSONDictionary objectForKey:key];
    NSString *title = [object objectForKey:@"**title**"];
    [theTitles addObject:title]
}

如果您只需要标题,那么这样做并没有真正的优势,而不是像第一个例子那样使用KVC,但如果您为每个对象做更复杂的工作,它可能是正确的选择。