如何获取JSON响应数组的所有索引值?

时间:2014-09-18 05:12:04

标签: ios json object

我需要获取JSON响应数组的所有索引值并维护单独的数组。下面我发布了我的JSON响应,我想让控制台输出看起来如下所示。请帮我。

response : [ {

        A =  [  {

                    name : "sons";
                    age = [
                                4
                          ];
                },
                {
                    name : "rondo";
                    age = [
                                2
                          ];
                },

             ];


           } ]

我需要存储单独的数组单独的值,如下面的控制台输出

2014-09-18 10:24:39.461 Myapp[1133:60b] RESULT : {
    name = "sons";
    age  = 4;
}
2014-09-18 10:24:39.462 Myapp[1133:60b] RESULT : {
    name = "rondo";
    age  = 2;
}

下面我试过但我知道我只能获得第0个索引值,但我需要从JSON响应数组中获取所有索引值:

myvalue = [NSString stringWithFormat:@"%@",[[[[responsData objectAtIndex:0] valueForKey:@"A"] objectAtIndex:0] valueForKey:@"name"]];

2 个答案:

答案 0 :(得分:0)

NSString *strName = (NSString *) [yourArray valueForKey:@"name"];
NSInteger age = [(NSNumber *) [yourArray valueForKey:@"age"] integerValue];

答案 1 :(得分:0)

如果要获取所有对象,请使用相应的键获取数组。然后通过根据数组计数迭代for循环将结果存储在另一个数组中。

NSArray *recordsArr = [[responsedata objectAtIndex:0] valueForKey:@"A"];

NSMutableArray *resultArray = [[NSMutableArray alloc] init];
for (int i = 0; i < [recordsArr count]; i ++) {
    NSMutableDictionary *recordDict = [[NSMutableDictionary alloc] init];

    [recordDict setObject:[[recordsArr objectAtIndex:i] valueForKey:@"name"] forKey:@"name"];
    [recordDict setObject:[[[recordsArr objectAtIndex:i] valueForKey:@"age"] objectAtIndex:0] forKey:@"age"];

    [resultArray addObject:recordDict];
}

NSLog(@"%@",resultArray);

输出:

2014-09-18 12:49:22.047 testprj[1044:60b] (
        {
        age = 4;
        name = sons;
    },
        {
        age = 2;
        name = rondo;
    }
)