iOS 6的JSON问题

时间:2013-06-18 18:33:14

标签: json parsing ios6

我正在尝试解析一个看起来像这样的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:]:索引0超出空数组的边界'

那么我应该把它放在valueForKeyPath中?

提前致谢

1 个答案:

答案 0 :(得分:-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);