0

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?

3
  • Your second line retrieves the results dictionary, but doesn't do anything with it. You need to assign the result of that expression to a variable of type NSDictionary * Commented Jun 27, 2015 at 7:12
  • Got it! NSDictionary * = parsedObject objectForKey:@"results"]; :) Commented Jun 27, 2015 at 7:18
  • Also for something as potentially error-prone as this, don't miss the opportunity to trap and report errors (i.e. check parsedObject != nil and then report the error (which you have set to NULL). Commented Jun 27, 2015 at 8:32

2 Answers 2

1

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"];
Sign up to request clarification or add additional context in comments.

1 Comment

Note: use objectForKey not valueForKey.
1

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.. :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.