开发者

JSON and nested NSDictionary

开发者 https://www.devze.com 2023-02-16 20:37 出处:网络
After parsing a JSON response, I get an NSDictionary containing other dictionaries which are the values for some keys not known in advance (308, 1):

After parsing a JSON response, I get an NSDictionary containing other dictionaries which are the values for some keys not known in advance (308, 1):

开发者_如何学Go{
"308":{
    "id":"308",
    .....

},
"1":{
    "id":"1",
    .....
     }
}

How do I use here valueForKey since I dont' know the keys? How to acces the nested dictionaries? Thanks!


NSDictionary *myDict;
...

NSArray *keys = [myDict allKeys]; //NSArray of dictionary's keys

for (id key in keys) //'foreach' loop for all keys
{
   id aValue = [myDict objectForKey: key]; //getting object from the dictionary
   if([aValue isKindOfClass:[NSDictionary class]])
   {
       //Object is a nested dictionary
       ...
   }
}


There are several way to iterate over an NSDictionary. One of them:

NSEnumerator *enumerator = [myDictionary objectEnumerator];
id value;

while ((value = [enumerator nextObject])) {
    /* do something with value */
}

Look "Enumerating Dictionaries" section in NSDictionary Class Reference for more alternatives.

0

精彩评论

暂无评论...
验证码 换一张
取 消