Search code examples
jsonparsingios6

JSON issues with iOS 6


I am trying to parse a json which looks like this:

[{"category": "anti-social-behaviour", "persistent_id": "", "location_subtype": "", "id": 23193805, "location": {"latitude": "52.6387452", "street": {"id": 883166, "name": "On or near Charnwood Street"}, "longitude": "-1.1136914"}, "context": "", "month": "2013-04", "location_type": "Force", "outcome_status": null}, 
{"category": "anti-social-behaviour", "persistent_id": "", "location_subtype": "", "id": 23195135, "location": {"latitude": "52.6288245", "street": {"id": 883098, "name": "On or near Roslyn Street"}, "longitude": "-1.1106710"}, "context": "", "month": "2013-04", "location_type": "Force", "outcome_status": null},'

I am trying to parse it with that way:

NSString *url = @"http://data.police.uk/api/crimes-at-location?date=2012-02&location_id=12345";

NSData *jsonDataString = [[NSString stringWithContentsOfURL:[NSURL URLWithString:url] encoding:NSUTF8StringEncoding error: nil] dataUsingEncoding:NSUTF8StringEncoding];

NSError *error = nil;

NSDictionary *results = [NSJSONSerialization JSONObjectWithData:jsonDataString options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:&error];

 NSArray *myResults = [results valueForKeyPath:@""];

 NSDictionary *bug = (NSDictionary *)[myResults objectAtIndex:0];

// And get its name
NSString *bugName = [bug objectForKey:@"category"];
NSLog(@"%@",bugName);

I get error: __NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array'

So what I should put in valueForKeyPath?

Thanks in advance


Solution

  • Sigh...

    NSData *jsonDataString = [[NSString stringWithContentsOfURL:[NSURL URLWithString:url] encoding:NSUTF8StringEncoding error: nil] dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *error = nil;
    
    NSArray* myResults = [NSJSONSerialization JSONObjectWithData:jsonDataString options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:&error];
    
    if (error != nil) {
        NSLog(@"%@", error);
    }
    
    NSDictionary *bug = (NSDictionary *)[myResults objectAtIndex:0];
    
    // And get its name
    NSString *bugName = [bug objectForKey:@"category"];
    NSLog(@"%@",bugName);