drlobo
drlobo

Reputation: 2159

IOS JSON Parsing Nested Data

Well I guess its an easy question (because I am only learning IOS recently).

Most of the tutorials that I have seen show simple JSON key value examples. However I am looking a JSON structure which has the following format:

So I have lets say a JSON page that displays something like:

loans: (
    {
    activity = "Personal Products Sales";
    "basket_amount" = 0;
    "bonus_credit_eligibility" = 1;
    "borrower_count" = 1;
    description =         {
        languages =             (
            en
        );
    };
    "funded_amount" = 0;
    id = 623727;
    image =         {
        id = 1457061;
        "template_id" = 1;
    };
    "loan_amount" = 475;
    location =         {
        country = Philippines;
        "country_code" = PH;
        geo =             {
            level = country;
            pairs = "13 122";
            type = point;
        };
        town = "Maasin City, Leyte";
    };
    name = Zita;
    "partner_id" = 145;
    "planned_expiration_date" = "2013-11-28T21:00:02Z";
    "posted_date" = "2013-10-29T21:00:02Z";
    sector = Retail;
    status = fundraising;
    use = "to buy additional stocks of soap, toothpaste, dish washing products, etc.";
},

So for example if I want to extract the name I understand the key pair ideas so I just do something like:

 NSError* error;
NSDictionary* json = [NSJSONSerialization
                      JSONObjectWithData:responseData //1

                      options:kNilOptions
                      error:&error];

NSArray* latestLoans = [json objectForKey:@"loans"]; //2
 NSDictionary* loan = [latestLoans objectAtIndex:0];
NSString *name = [loan objectForKey:@"name"];

And then *name should evaluate to : Zita.

But my question is ....

1) What wizardry do I need to do in order to get access data deep inside the structure like "level = country;" (the level is located inside "geo" which is located inside "location")

Can someone explain how to do this ?

Upvotes: 0

Views: 1887

Answers (1)

Grzegorz Krukowski
Grzegorz Krukowski

Reputation: 19872

Exactly the same way as you're doing right now :)

NSDictionary* loan = [latestLoans objectAtIndex:0];
NSDictionary* location = [loan objectForKey:@"location"];
NSDictionary* geo = [locationobjectForKey:@"geo"];
NSString* level = [geo objectforKey:@"country"];

or shorter:

NSDictionary* loan = [latestLoans objectAtIndex:0];
NSString* level = loan[@"location"][@"geo"][@"level"];

Upvotes: 3

Related Questions