iosobjective-cjsonios7afnetworking-2

best way to test for JSON null value in JSON being returned with AFNetworking 2.0


I have a JSON payload being returned that could either be null or value. Like:

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

or when there is a current_instore_announcement:

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

I am using AFNetworking 2.0 and want to either show the current_isntore_announcement if it exists or do nothing if it returns null.

How would I properly check for the existence of the current_instore_anncouncement? I have:

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);
}
}

but I get the following error:

[NSNull notNullObjectForKey:]: unrecognized selector sent to instance 

Edit #1

It looks like the best way is to check for it not being NSNull. Like so:

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

or to create an addition to NSDictionary like this:

#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;
}

Any other / better ideas?


Solution

  • i use following methods:

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