An Interesting Approach to handling NSNulls in JSON objects

I was the lead developer of the Lot18 app – Lot18 is an e-commerce wine marketplace. In that role, I used the web REST interface to retrieve product, inventory, and reviews.  While processing thousands of different objects I’d occasionally stumble on a crash or UI anomaly caused by a NSNull null object buried deep in some dictionary or array.

My first approach to deal with this was to created mutable arrays and dictionaries, and walk the full tree, looking for dictionaries. It worked, but just kept getting more and more complex, and at some point you realize you’ve taken the wrong approach.

The light bulb went on, and I found a method that really worked well: add a category to NSNull. Thinking about it, the issue wasn’t the NSNull null per se, but the methods that my UITableView code would throw it at: asking for a count, or a property, or a value. A prime example of this was inventoryCount. If a product had entered stock, the number could be anywhere from negative (yeah! had to deal with that in a crash!), zero, or some large positive number. However, if the product had not been stocked at least once, the return was a NSNull null object.

So, my approach was to create a NSNull category and essentially deal with any odd method, and return a sane value:


@implementation NSNull (JSON)
- (NSUInteger)length { return 0; }
- (NSInteger)integerValue { return 0; };
- (CGFloat)floatValue { return 0; };
- (NSString *)description { return @"0(null)"; }
- (NSArray *)componentsSeparatedByString:(NSString *)separator { return @[]; }
- (id)objectForKey:(id)key { return nil; }
- (BOOL)boolValue { return NO; }
@end

There well may be other methods that need to be added to this list, but the above was sufficient for me. Note the returned description string – it makes it clear when NSLogging objects that the value was NSNull null.

[ Note that this post was extracted from an earlier StackOverFlow answer.]