IOS / Objective-C:检测jsonResults是否包含键值对

时间:2017-07-17 15:24:14

标签: ios json null

在某些情况下,我尝试解析的JSON对象包含某个键。在其他情况下,它没有。

当我尝试访问对象的键值对时,无论键是否存在,它自然会导致崩溃。因此,我试图预先测试密钥是否存在。但是,NSNull类测试由于某种原因不起作用。有人可以建议使用正确的测试来检测密钥是否存在吗?

这是我的编辑代码,用于筛选出无效的空案例:

NSDictionary *jsonResults = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
         NSLog(@"Results of post: %@", jsonResults);

 if ([jsonResults[@"response"][@"insert_id"]isKindOfClass:[NSNull class]]){
                    NSLog(@"insert id is null");}
else {
//EVEN WHEN I KNOW THAT THERE IS no insert_id key, I get to this code suggesting test above not working
    //Access insert_id value using Key value and so something with it
NSInteger insertID = [jsonResults[@"response"][@"insert_id"] integerValue];
    }

1 个答案:

答案 0 :(得分:0)

最后它是一个NSDictionary,如果你研究NSDictionary是否包含一个密钥,你会找到更多的帮助。

如果密钥不存在,

objectForKey将返回nil。 您可以尝试:

if ([jsonResults objectForKey:@"response"] valueForKey:@"insert_id"] != nil {
    NSLog(@"insert id is not null");
}

或确保您的回复是字典

NSDictionary *response = jsonResults[@"response"];
if ([response isKindOfClass:[NSDictionary class]]) {
   if (jsonResults[@"response"][@"insert_id"] != nil {
    NSLog(@"insert id is not null");
   }
}