如何通过从JSON获取的以下字典进行循环?我如何循环获取只有ID 0001,0002?如何从JSON中获取循环NSDictionary?
{
0001 = {
userName = "a";
photo = "";
};
0002 = {
userName = "b";
photo = "";
};
}
如何通过从JSON获取的以下字典进行循环?我如何循环获取只有ID 0001,0002?如何从JSON中获取循环NSDictionary?
{
0001 = {
userName = "a";
photo = "";
};
0002 = {
userName = "b";
photo = "";
};
}
我找到了答案。我已经尝试了下面的代码,但它提供了所有的数据。 因为我得到的json是worng格式。
for (NSString *key in Dict) {}
试试这个方法...
获取所有按键
NSArray *a=[yourDictionary allKeys];
NSArray *keys = [dictionary allKeys];
试试这个。您将获得数组中的所有密钥。然后你可以相应地在NSString
。
您环路直通的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
或者使用fast enumeration:
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.
}
+1为漂亮的解释:) –
*“有循环通一的NSDictionary没有真正的方法” * - 这是不正确的。 'for(NSString * key in dict)'* *列举字典键,所以你不需要'allKeys'。并且有'enumerateKeysAndObjectsUsingBlock:'... –
@MartinR你是对的,它也会通过键循环 – rckoenes
另一种方法是使用enumerateKeysAndObjectsUsingBlock:
API来枚举密钥和对象,
用法很简单,
[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(@"Key: %@, Value:%@",key,obj);
if([key isEqualToString:@"0001"]) {
//Do something
}
// etc.
}];
希望帮助!
'NSDictionary'中的键不必是'NSString'类型,因为在你的例子中键将会是'NSNumbers' – rckoenes