json - 如何使用objective-c检查JSON的结构
问题描述
我有一个结构为字典数组的 JSON。
正常的结构会是这样的,(在解析成数组之后):
[0] - [NSDictionary *] 3 key/value pairs
[0] departure - 1 element
-> key @"city"
-> value @"New York"
[1] arrival -1 element
-> key @"city"
-> value @"Atlanta"
[2] bus -3 key/values pairs
-> key @"bus"
-> value (NSDictionary *) 3 key/value pairs
[0] @"number" (long) 123
[1] @"driver" @"smith"
[2] @"type" @"40 seat coach"
但是,如果您解析具有结构但缺少一个关键元素(即最后一个元素)的“坏”JSON
[0] - [NSDictionary *] 3 key/value pairs
[0] departure - 1 element
-> key @"city"
-> value @"New York"
[1] arrival -1 element
-> key @"city"
-> value @"Atlanta"
[2] bus -3 key/values pairs
-> key @"bus"
-> value (NSNull *) 0x8976656
-> NSObject
如果我尝试在公共汽车下查询司机的姓名,它会崩溃。我试图测试 null 但不起作用。它在请求期间也不会抛出错误(NSURLSessionDataTask)。你如何防范这种情况?
NSArray *busCompany = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err];
myBuses =[[NSMutableDictionary]alloc]init];
for (NSDictionary *companiesDict in busCompany) {
myBuses = companiesDict[@"bus"];
if(myBuses) { //also tried if(myBuses != NULL)
NSString *driverName = [myBuses ForKey: @"driver"];
}
}
它给了我[NSNULL objectforkey]
错误。
解决方案
推荐阅读
- python - 创建用于加载磁盘映像文件的文件树的 GUI
- html - 不知道如何编辑溢出的列表项
- python - 用诗歌生成 *.dist-info/entry_points.txt
- python - 展平由对象组成的列表或没有 isintance 的列表
- html - IOS不能自动播放视频
- javascript - 变量和函数中的 Javascript 范围
- bash - 使用“on-the-fly”参数执行 PGP 加密的 shell 脚本
- drake - 如何在没有模拟的情况下可视化新姿势,使用 VTKRenderer
- arrays - PostgreSQL:在 WITH 构造中使用列作为数组
- html - CSS自动填充顶部和底部以始终覆盖高度