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

时间:2015-07-23 12:02:25

标签: ios objective-c json

我试图从嵌套的JSON响应中获取一些键和值。下面我提到了我的JSON响应结构,我需要从下面的响应中获取所有keys(Red, Green)和键values(Color and ID),并加载到数组中以获取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];

2 个答案:

答案 0 :(得分:1)

我已经通过编码创建了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"]);
        }

我认为你想要一样,它会对你有帮助!

答案 1 :(得分:0)

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

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

例如,如果您需要按color_id排序的颜色数组,您可以自己对其进行排序:

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