如何从嵌套的JSON获取值 – Objective c

我想从下面嵌套的JSON响应中获得一些键和值。 下面我提到了我的JSON响应结构,我需要从下面的响应中获取所有的keys(Red, Green)和键值values(Color and ID) ,并加载到Array for tableview单元格值。

仅供参考:我已经尝试了使用NSDictionary但我得到所有的时间无序的价值观。 我还需要获得有序的值。 请帮帮我!

 { response: { RED: { Color: "red", color_id: "01", }, GREEN: { Color: "green", color_id: "02", } }, Colorcode: { }, totalcolor: "122" } 

我的代码:

  NSError *error; NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; NSArray *responsData = [jsonDictionary objectForKey:@"response"]; NSLog("%@",[responsData objectAtIndex:0]); // here I am getting bad exception NSDictionary *d1 = responsData.firstObject; NSEnumerator *enum1 = d1.keyEnumerator; NSArray *firstObject = [enum1 allObjects]; 

我已经通过编码创build了JSON数据,所以不要只考虑下面的答案

  /// Create dictionary from following code /// it just for input as like your code NSMutableDictionary * dict = [[NSMutableDictionary alloc] init]; NSMutableDictionary * innr = [[NSMutableDictionary alloc] init]; [innr setObject:@"red" forKey:@"Color"]; [innr setObject:@"01" forKey:@"color_id"]; NSMutableDictionary * outer = [[NSMutableDictionary alloc] init]; [outer setObject:innr forKey:@"RED"]; innr = [[NSMutableDictionary alloc] init]; [innr setObject:@"green" forKey:@"Color"]; [innr setObject:@"02" forKey:@"color_id"]; [outer setObject:innr forKey:@"GREEN"]; [dict setObject:outer forKey:@"response"]; // ANS ------ as follow // get keys from response dictionary NSMutableArray * key = [[NSMutableArray alloc] initWithArray:[dict[@"response"] allKeys]]; // sort as asending order NSSortDescriptor* sortOrder = [NSSortDescriptor sortDescriptorWithKey: @"self" ascending: YES]; key = (NSMutableArray *)[key sortedArrayUsingDescriptors: [NSArray arrayWithObject: sortOrder]]; // access inner data from dictonary for (NSString * obj in key) { NSLog(@"%@",dict[@"response"][obj][@"Color"]); NSLog(@"%@",dict[@"response"][obj][@"color_id"]); } 

我想你想要相同的,它会帮助你!

如果你坚持使用这个JSON,如果你想要一个值的数组,你可以执行以下操作:

 NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; NSDictionary *response = json[@"response"]; NSArray *colors = [response allValues]; 

如果你需要color_idsorting的颜色数组,例如,你可以自己sorting:

 NSArray *sortedColors = [colors sortedArrayUsingDescriptors:@[[[NSSortDescriptor alloc] initWithKey:@"color_id" ascending:TRUE]]];