Reputation: 53
I have a very complex JSON data. And I tried to parse using objective c programming. The JSON data looks like the following (Here, I presented the simple format to explain. But it has very deep leveling):
{
"university": "CUNY",
"results": {
"Engineering": 200,
"Computer Science": 298,
"Life Science": 28
}
}
Using NSJSONSerialization
, I tried to solve this and I use the following code:
NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
[parsedObject objectForKey:@"results"];
And getting the result. But I need a dictionary like myResultDict
which will be made form the results
so that I can implement other functionality.
Can anybody give me a small hint how to do that?
Upvotes: 0
Views: 1134
Reputation: 4550
Try this method:
NSDictionary *dic = @{@"university": @"CUNY", @"results" : @{@"Engineering": @200, @"Computer Science": @298, @"Life Science": @28}};
[self getSubDictionaryWithDictionary:dic];
This method only logs the values inside NSDictionary
, if you want to handle NSArray
kind of class, up to you.. :)
- (void)getSubDictionaryWithDictionary:(NSDictionary *)dictionary
{
for (id key in [dictionary allKeys])
{
id object = [dictionary objectForKey:key];
NSLog(@"key:%@ value:%@",key, object);
if ([object isKindOfClass:[NSDictionary class]])
{
[self getSubDictionaryWithDictionary:object];
}
}
}
This extract all the dictionary inside the nested dictionary, you can modify it depending from what you need.. :)
Hope this is helpful.. Cheers.. :)
Upvotes: 1
Reputation: 54
When you get the parsed data by using NSJSONSerialization
it will give you parsed dictionary with multiple key-value pairs.
Then by fetching results key you can get your result dictionary.
For example:
NSDictionary *myResultDict = [parsedDictionary objectForKey:@"results"];
Upvotes: 1