我尝试解析这个:
{"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"];
但是这个家伙来打扰我了:
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x9e7d010'
所以我想知道我做错了什么。我尝试用谷歌搜索它,很多人说当数据实际上是字典时我假设使用数组。真的吗?那么我需要做什么?
最佳答案
改变
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
保存事件列表(数组)。并在从 events
访问 objectAtIndex:
之前进行计数检查。
关于ios - 解析失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25282193/