-2

如何遍历从 JSON 获得的以下字典?我如何循环以仅获取 id 0001、0002?

{
    0001 = {
      userName = "a";
      photo = "";
    };
    0002 = {
      userName = "b";
      photo = "";
    };
}
4

5 回答 5

3

你遍历NSDictionary键:

NSArray *keys = [dictionary allKey];

for (id *key in keys ) {
    NSDictionary *userPhoto = [dictionary objectForKey:key];
    // here you can either parse the object to a custom class
    // or just add it to an array.
}

或者直接在 上使用快速枚举NSDictionary

for (id *key in dictionary ) {
    NSDictionary *userPhoto = [dictionary objectForKey:key];
    // here you can either parse the object to a custom class
    // or just add it to an array.
}

每个键,您可以检索对象。

或使用enumerateKeysAndObjectsUsingBlock:

[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    // Here you can access the object and key directly.
}
于 2013-10-17T13:26:56.470 回答
1

试试这个方法...

获取所有密钥

NSArray *a=[yourDictionary allKeys];
于 2013-10-17T13:26:36.050 回答
0
NSArray *keys = [dictionary allKeys];

试试这个。您将获得数组中的所有键。然后你可以NSString相应地把它们放进去。

于 2013-10-17T13:26:51.663 回答
0

另一种选择是使用enumerateKeysAndObjectsUsingBlock:api 枚举键和对象,

用法很简单,

[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    NSLog(@"Key: %@, Value:%@",key,obj);
    if([key isEqualToString:@"0001"]) {
        //Do something
    }
    // etc.
}];

希望有帮助!

于 2013-10-17T13:35:02.187 回答
-1

我找到了答案。我已经尝试过使用以下代码,但它提供了所有数据。因为我得到的json是wearg格式。

    for (NSString *key in Dict) {}  
于 2013-10-18T04:40:20.883 回答