IOS: How to check json object is not null

435 views Asked by At

I am getting an error with the following code when some json is null even though I am trying to check that first:

Edit: Preceding Code:

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

Is there a better way to check Json is not null?

Here is error output:

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

There are 4 answers

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

}
3
Helge Becker On
if ([json objectForKey:@"items"] != nil) {
        NSLog(@"got here");
        NSLog(@"json%@",json);
        latestItems = [[json objectForKey:@"items"]mutableCopy];
}

NULL or nil is not a class, but a convention. The memory adress 0 is the point where a cpu starts to execute code during cold start. Therefore no object can have this address in memory.

By the book should the json not have the key @"items" if the value of @"items" is NULL. The missing key indicates a NULL value.

0
gnasher729 On

I don't know what's wrong with your code, but the easiest way to check for a JSON null value if you are sure that json is a dictionary is:

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

[NSNull null] always returns the same instance of NSNull. There is never more than one instance of NSNull, so you can actually use pointer comparison to check whether an object is an NSNull instance.

0
iOS77 On
if (json && [json isKindOfClass:[NSDictionary class]]) {
    //your code here
} else {
    //invalid json
}