NSDictionaries and Nested JSON

2019-02-20 18:12发布

问题:

I am able to create a NSDictionary from a JSON file no problem, what I need to know is how to do nested JSON strings?? See Example:

{
 "data": [
  {
     "id": "270639882984792_306265986160413",
     "from": {
        "category": "Non-profit organization",
        "name": "My Facebook Page",
        "id": "270639882984792"
     },

So this is part of a massive JSON file, but how do I set it up, so that I can call the "name" key from the "from" key - I know how to call the "id" key from the "data" key, but the one I want is a level deeper.

Thanks in advance:-)

EDIT - here is some iOS code I started working on:

NSDictionary *items = [json objectForKey:@"data"];

NSArray *items2 = [items objectForKey:@"from"];
// NSDictionary *item = [items objectAtIndex:1];

NSMutableArray *story = [NSMutableArray array];

for (NSDictionary *item in items2 )
{

    if([item objectForKey:@"name"] || [item objectForKey:@"name"] != nil || [[item objectForKey:@"name"] length]>0){
        [story addObject:[item objectForKey:@"name"]];
    }

    NSLog(@"ITEM - %@", [item objectForKey:@"name"]);

}

回答1:

Try this:

NSDictionary* data= json[@"data"];
NSDictionary* from= [data[0] objectForKey: @"from"];
NSString* name= from[@"name"];

If you just want the name you're fine, if instead you need all the data, I suggest to create an object that is able to hold a value for every dictionary entry. You access to "id" and "category" the same way I shown, just using a different key.