zztop zztop - 10 months ago 71
iOS Question

IOS: Detecting NSNull from JSON Not Working

The following code designed to catch an NSNull in Json results is throwing an exception when the response is null.

NSDictionary *jsonResults = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"jsonResults are:%@",jsonResults);
if (![jsonResults isKindOfClass:[NSNull class]]&&!
[jsonResults[@"response"][@"insert_id"]isKindOfClass:[NSNull class]]&&!
//do something

When the exception occurs, the line beginning
if (![json...
is in green and the error message reads:

Results: {
code = 400;
response = "0(NSNull)";
2016-05-26 07:18:06.327 idaru[385:60b] -[NSNull
objectForKeyedSubscript:]: unrecognized selector sent to instance
2016-05-26 07:18:06.329 myapp[385:60b] *** Terminating app due to
uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull
objectForKeyedSubscript:]: unrecognized selector sent to instance

Can anyone suggest what could be wrong here?

Of note, I do have a category that supposedly converts NSNulls into 0s. Not sure how this interacts with above but here it is:

@implementation NSNull (JSON)

- (NSUInteger)length { return 0; }

- (NSInteger)integerValue { return 0; };

- (float)floatValue { return 0; };

- (NSString *)description { return @"0(NSNull)"; }

- (NSArray *)componentsSeparatedByString:(NSString *)separator { return @[]; }

- (id)objectForKey:(id)key { return nil; }

- (BOOL)boolValue { return NO; }



try like this,

  if (![jsonResults isKindOfClass:[NSNull class]] || !(jsonResults==nil)) {

    if (![jsonResults[@"response"][@"insert_id"]isKindOfClass:[NSNull class]]) {

        //Do your task here


It is because if your jsonResults is null then it can't check for [jsonResults[@"response"][@"insert_id"] !!

Hope this will help :)