ios - 解析失败

标签 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"];

但是这个家伙来打扰我了:

* 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/

相关文章:

ios - 主线程执行耗时操作如何影响UI刷新

未安装应用程序时iOS Twitter登录

objective-c - 多次用新数据刷新 NSTableView

ios - UIView autoresizingMask 用于固定左右边距和灵活宽度

ios - 从 NSJSONSerialization 返回的对象可以不同

ios - 如何使用 Swift 将音频文件保存到 iCloud?

ios - Sprite Kit-施加静态脉冲

objective-c - UIColor、UIFont 等的外部常量

ios - NSJSONSerialization将\n添加到JSON字符串的开头和结尾

ios - 在 iOS 中使用数组解析 JSON 时出错