get values of particular key in nsdictionary

Minkle Garg picture Minkle Garg · Apr 26, 2013 · Viewed 64.4k times · Source

I saved the json parsing result in a dictionary which look like:

{
 "statusCode":"200",
"body":[
  {
     "status":"success",
     "remarks":null
  }
],

"data":[
     "abcd":[
        {
           "category":"a",
           "title":"b",
           "id":"24"
        },
        {
           "category":"c",
           "title":"crd",
           "id":"65"
        },
        {
           "category":"ds",
           "title":"sd",
           "id":"18"
        }

     ]
  },
  {
     "efgh":[
        {
           "category":"ds",
           "title":"sd",
           "id":"18"
        },
        {
           "category":"sd",
           "title":"sd",
           "id":"1"
        }

                             ]
  },
  {
     "ijkl":[
        {
           "category":"ds",
           "title":"sd",
           "id":"18"
        },
        {
           "category":"sd",
           "title":"sd",
           "id":"1"
        }

     ]
  }
 ]
}

The data for key @"data" can be saved into an array by using

NSMutableArray *getdata=[[NSMutableArray alloc]init];
getcat=[results objectForKey:@"data"];

Now what should I do for the values(category, title, id) inside the first index i.e. "abcd".

If anyone has any knowledge please look upon that.

Thanks to all.

Answer

Anoop Vaidya picture Anoop Vaidya · Apr 26, 2013

Following will give you the desired object

NSDictionary *dict=[results valueForKeyPath:@"data.abcd"][0];

For individual:

NSString *categoryString=[[results valueForKeyPath:@"data.abcd"][0] objectForKey:@"Category"];
NSString *idString=[[results valueForKeyPath:@"data.abcd"][0] objectForKey:@"id"];
NSString *titleString=[[results valueForKeyPath:@"data.abcd"][0] objectForKey:@"title"];

Also,

NSString *categoryString=dict[@"Category"];
NSString *idString=dict[@"id"];
NSString *titleString=dict[@"title"];