测试AFNetworking 2.0返回的JSON中JSON空值的最佳方法



我返回了一个JSON负载,该负载可能为null或value。类似:

post: {
header:"here is my header",
current_instore_anncouncement: null
}

或者当存在current_instore_announcement:时

post: {
header:"here is my header",
current_instore_anncouncement: {header: "announcement header"}
}

我使用的是AFNetworking 2.0,如果current_isntore_announcement存在,我想显示它,如果它返回null,我想什么都不做。

如何正确检查current_instore_anncouncement的存在?我有:

NSDictionary *current_instore_announcement=[result objectForKey:@"current_instore_anncouncement"];
if(current_instore_announcement){
InstoreAnnoucement *splashAnnouncement = [[InstoreAnnoucement alloc] initWithAttributes:current_instore_announcement];
if(splashAnnouncement){
NSLog(@"theres an instore announcement");
}else{
NSLog(@"nadda = instore announcement with %@",current_instore_announcement);
}
}

但我得到以下错误:

[NSNull notNullObjectForKey:]: unrecognized selector sent to instance 

编辑#1

看起来最好的方法是检查它是否为NSNull。像这样:

if(![current_instore_announcement isEqual:[NSNull class]]){

或者创建一个NSDictionary的添加,如下所示:

#import "NSDictionary+Additions.h"
@implementation NSDictionary (Additions)
- (id)notNullObjectForKey:(id)aKey {
id obj = [self objectForKey:aKey];
if ([obj isKindOfClass:[NSNull class]]) {
return nil;
}

return obj;
}

还有其他更好的想法吗?

i使用以下方法:

if(![current_instore_announcement isEqual:[NSNull class]]){
// Not null
}
else{
// null
}

检查这一点的好方法是使用以下方法。请检查这个:

- (BOOL) hasValue:(id)object {
if(object!=nil && (NSNull *)object != [NSNull null])    {
// Check NSString Class
if([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSMutableString class]]) {
if([object length]>0) {
return YES;
}
} 
// Check UIImage Class
if([object isKindOfClass:[UIImage class]]){
if ([object CGImage]!=nil) {
return YES;
}
}
// Check NSArray Class
if ([object isKindOfClass:[NSArray class]] || [object isKindOfClass:[NSMutableArray class]]) {
if ([object count] > 0) {
return YES;
}
}
else {
return YES;
}
}
return NO;
}

并且您必须每次检查json响应中的每个对象。

您可以使用[myDisctionary allKeys];进行检查

例如:

NSDictionary *current_instore_announcement=[result objectForKey:@"current_instore_anncouncement"];
// get the keys
NSArray *keys = [current_instore_announcement allKeys];
if([keys count]>0){
// do something with the dictionary.
}else
// Null Values
NSDictionary *current_instore_announcement=[result objectForKey:@"current_instore_anncouncement"];
if ([current_instore_announcement isKindOfClass:[NSDictionary class]]){
//nil or null will not be here, and just do NSDictionary parsing here
}

否则:

if (![current_instore_announcement isKindOfClass:[NSNull class]]){
//not null class will be here, NSDictionary, nil, empty string will all be parsed here
}