如何循环从 JSON 获得的 NSDictionary



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

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

你循环通过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.
}

试试这个方式...

获取所有密钥

NSArray *a=[yourDictionary allKeys];
NSArray *keys = [dictionary allKeys];

试试这个。您将获得数组中的所有密钥。然后你可以相应地将它们NSString.

另一种替代方法是使用 enumerateKeysAndObjectsUsingBlock: api 枚举键和对象,

用法非常简单,

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

希望对您有所帮助!

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

    for (NSString *key in Dict) {}  

最新更新