无法解析

时间:2014-08-13 09:04:24

标签: ios objective-c nsjsonserialization

我试图解析这个:

{"event":[{"event_id":"9","title":"event 10","welcome_logo":"20140715130727_252.png"}],"succeed":1}

这是我的代码:

NSString *strURL=[NSString stringWithFormat:@"http://loc**host/summit/event_login.php"];
NSData *dataURL=[NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *strResult=[[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSArray *jsonArray=[NSJSONSerialization JSONObjectWithData:dataURL options:0 error:nil];
NSDictionary *element=[jsonArray objectAtIndex:0];
NSString *title = [element objectForKey:@"title"];
NSString *image = [element objectForKey:@"welcome_logo"];

但这个家伙来了,让我不安:

  

* 由于未捕获的异常终止应用程序' NSInvalidArgumentException',原因:' - [__ NSCFDictionary objectAtIndex:]:无法识别的选择器发送到实例0x9e7d010'

所以我想知道我做了什么我做错了。我试图谷歌它,许多人说我假设数据实际上是一个字典时使用数组。真的吗?那么我需要做什么?

1 个答案:

答案 0 :(得分:1)

更改

NSArray *jsonArray=[NSJSONSerialization JSONObjectWithData:dataURL options:0 error:nil];
NSDictionary *element=[jsonArray objectAtIndex:0];

NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:dataURL options:0 error:nil];
NSArray *events = [jsonDict objectForKey:@"event"];
if ([events count] > 0) {
    NSDictionary *element=[events objectAtIndex:0];
}

因为你的json数据是字典的形式。并且event保存事件的列表(数组)。在从objectAtIndex:访问events之前进行统计检查。