Parsing JSON and Checking for Null

Parsing JSON and Checking for Null
5 years ago 0
Posted in: Programming

File this under the “not very obvious” category. A JSON response comes back and you’re parsing it like a champ. You even put in the regular null checking like the good programmer you are.


NSString * value = [json objectForKey:@"key"];
if (value == nil)
    return NO;

double number = [value doubleValue];

Well, that just doesn’t work. Apparently the JSON isn’t translated into a nil as I expected. So instead of kicking out, it goes on to the next line and attempts to extract a double value out, and then exception time!

It turns out that it is a nil of sorts. It’s just a NSNull class. Go figure.


NSString * value = [json objectForKey:@"key"];
if ([value isKindOfClass:[NSNull class]])
    return NO;

double number = [value doubleValue];

So instead a check against the NSNull class needs to be done.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *