0

我被困在 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"}}

问题是我想在表格视图中显示所有标题。我可以通过使用键 0、1、2 获得单个标题。但我希望我解析后立即显示所有标题

请大家帮帮我,在此先感谢。

4

2 回答 2

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
于 2012-10-08T05:29:18.567 回答
2

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

无论如何,你所拥有的相当于一本字典。如果您将其作为 NSDictionary 调用myJSONDictionary,您可以说:

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 并没有真正的优势,但如果您对每个对象都有更复杂的工作要做,它可能是正确的选择。

于 2012-10-08T05:23:20.750 回答