1

当某些 json 为空时,即使我尝试先检查以下代码,我也会收到以下代码错误:

编辑:前面的代码:

NSData* data = [NSData dataWithContentsOfURL: kItemsURL];
            //previous line grabed data from api.
            if (data) {
                [self performSelectorOnMainThread:@selector(fetchData:) withObject:data waitUntilDone:YES];
}
- (void)fetchData:(NSData *)jsonFeed {
     NSError* error;
        NSDictionary* json = [NSJSONSerialization JSONObjectWithData:jsonFeed                                                           options:kNilOptions                                                             error:&error];

//Original code provided
    if (![[json objectForKey:@"items"] isKindOfClass:[NSNull class]]) {
            NSLog(@"got here");
            NSLog(@"json%@",json);
            latestItems = [[json objectForKey:@"items"]mutableCopy];
    }

有没有更好的方法来检查 Json 不为空?

这是错误输出:

2016-05-03 13:05:43.820 testApp[407:60b] got here
2016-05-03 13:05:43.821 testApp[407:60b] json{
    items = "<null>";
}
NSNull mutableCopyWithZone:]: unrecognized selector sent to instance 0x3ac26a70
2016-05-03 13:05:43.825 ChallengeU[407:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull mutableCopyWithZone:]: unrecognized selector sent to instance 0x3ac26a70'  
4

4 回答 4

0
if (![json[@"items"] isEqual:[NSNull null]]) {
//do your stuff in here

}
于 2016-05-03T21:10:36.303 回答
0

我不知道您的代码有什么问题,但是如果您确定json 是字典,那么检查 JSON 空值的最简单方法是:

if (json [@"items"] != [NSNull null]) { ... }

[NSNull null]总是返回相同的 NSNull 实例。NSNull 实例永远不会超过一个,因此您实际上可以使用指针比较来检查对象是否为 NSNull 实例。

于 2016-05-03T22:52:36.923 回答
-1
if (json && [json isKindOfClass:[NSDictionary class]]) {
    //your code here
} else {
    //invalid json
}
于 2016-05-04T03:42:50.733 回答
-2
if ([json objectForKey:@"items"] != nil) {
        NSLog(@"got here");
        NSLog(@"json%@",json);
        latestItems = [[json objectForKey:@"items"]mutableCopy];
}

NULL 或 nil 不是一个类,而是一个约定。内存地址 0 是 cpu 在冷启动期间开始执行代码的点。因此,任何对象都不能在内存中拥有该地址。

如果 @"items" 的值为 NULL,那么 json 是否应该没有键 @"items"。缺少的键表示 NULL 值。

于 2016-05-03T21:36:28.647 回答