Parsing Complex JSON (Navigating the hierarchy of objects it produces) in Objective C

497 Views Asked by At

I am developing an app based on school menus and dishes where I am stuck is in parsing complex/nested json

Sample Json URL : Json Data

So far I have just done this as mentioned in below code using SBJSON:

dispatch_async(dispatch_get_main_queue(),^ {

    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus networkStatus = [reachability currentReachabilityStatus];
    if (networkStatus == NotReachable) {
        [self.view setUserInteractionEnabled:YES];
        [HUD hideUIBlockingIndicator];

    }

    else
    {

        Url =[NSString stringWithFormat:@"http://private-e8e699-yumyummi.apiary-mock.com/districts/115/schools/43/menus/"];
        checkData =[[NSMutableArray alloc]init];
        URLRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:[Url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
        NSURLResponse *response = nil;
        NSError  *error = nil;
        NSData  *data = [NSURLConnection sendSynchronousRequest:URLRequest returningResponse:&response error:&error];
        NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        SBJsonParser* parser = [[SBJsonParser alloc] init];

        NSError *jsonError;
        if(jsonError == nil)
        {
            id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];


            NSLog(@"%@",json);

            NSDictionary *data = [json objectForKey:@"data"];            
    }
});
1

There are 1 best solutions below

0
user2889962 On

If your problem is that you don't know the exact structure of the data in your json, you can use something like:

if([json isKindOfClass:[NSDictionnary class]) {
    // actions for a dictionnary
    id branch = json[@"your key"];
} else if([json isKindOfClass:[NSArray class]) {
    // actions for an array
    id branch = json[index];
}

Also the line if(jsonError == nil) make no sense, you sould do this after doing [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];