2013-06-18 56 views
0

我试图分析JSON它看起来像这样:与iOS JSON问题6

[{"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放在哪里?

在此先感谢

+0

那么,什么更多信息你想......你试图从一个空数组得到一个对象。你确定你的JSON是一个数组而不是一个对象吗? – Rob

+1

请发布**实际代码**您在第一行写的是**无效的JSON。** – 2013-06-18 18:34:33

+0

“结果”不是字典。 NSLog它,你会看到它是一个数组。 –

回答

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

仍然无法正常工作。网址是:NSString * url = @“http://data.police.uk/api/crimes-at-location?date=2012-02&location_id=12345”; – BlackM

+0

@ user776720 - 该查询产生一个空数组,所以你会得到数组边界错误。如果您放弃日期(或将其更改为2013-04),您会收到一起车辆犯罪。 –

+0

我不好意外使用了错误的URL来测试你的解决方案!谢谢 – BlackM