user4038028
user4038028

Reputation:

Parse JSON to get value for key

I am trying to retrieve a value from JSON but not getting it. It seems to have something to do with the difference between the response in the JSON and the key. Can anyone suggest how to do this?

 NSDictionary *jsonResults = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"Results: %@", jsonResults); 
/* This logs to console as follows:
Results: {
    code = 200;
    error = "<null>";
    response =     {
        "insert_id" = 3861;
    };
        NSLog(@"insert_id%@",[jsonResults objectForKey:@"insert_id"]);
//This logs as 
insert_id (null)

Upvotes: 0

Views: 50

Answers (2)

vadian
vadian

Reputation: 285039

The requested value is in a nested dictionary with key response

NSLog(@"insert_id: %@",jsonResults[@"response"][@"insert_id"]);

Upvotes: 1

rmaddy
rmaddy

Reputation: 318774

Look at the output of jsonResults. The curly braces indicate a dictionary. And note the value of the "response" key. Its value has further curly braces. This means it is a nested dictionary.

The "insert_id" key is nested inside the "response" key's dictionary. You need:

NSLog(@"insert_id%@",jsonResults[@"response"][@"insert_id"]);

Also note the use of modern syntax. It's easier to read and write.

Upvotes: 2

Related Questions