0

我正在尝试解析一个看起来像这样的 json:

[{"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},'

我正在尝试用这种方式解析它:

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);

我收到错误:__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array'

那么我应该在 valueForKeyPath 中放入什么?

提前致谢

4

1 回答 1

-1

叹...

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);
于 2013-06-18T20:44:13.513 回答