Skip to content

Instantly share code, notes, and snippets.

@mattt
Created November 13, 2012 21:51
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattt/4068640 to your computer and use it in GitHub Desktop.
Save mattt/4068640 to your computer and use it in GitHub Desktop.
static NSInteger NSJSONReadingFuckNSNulls = (1UL << 3);
@implementation NSJSONSerialization (FuckNulls)
+ (void)load {
Method originalMethod = class_getClassMethod(self, @selector(JSONObjectWithData:options:error:));
IMP swizzledImplementation = imp_implementationWithBlock([^id (id _self, NSData *_data, NSJSONReadingOptions _opt, NSError **_error){
NSInputStream *stream = [NSInputStream inputStreamWithData:_data];
[stream open];
id JSON = [self JSONObjectWithStream:stream options:_opt error:_error];
if ((_opt & NSJSONReadingFuckNSNulls) && [JSON isKindOfClass:[NSDictionary class]]) {
NSMutableDictionary *mutableJSON = [JSON mutableCopy];
[JSON enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([obj isEqual:[NSNull null]]) {
[mutableJSON removeObjectForKey:key];
}
}];
JSON = mutableJSON;
}
return JSON;
} copy]);
method_setImplementation(originalMethod, swizzledImplementation);
}
@end
@mattt
Copy link
Author

mattt commented Nov 13, 2012

In lieu of invoking the supersequent (I couldn't figure out why imp_getBlock() wasn't working from the original implementation)...

@bdittmer
Copy link

Shouldn't this also check for NSDictionary's and recursively remove nulls there as well?

@0xced
Copy link

0xced commented Nov 14, 2012

I would use a much higher constant for NSJSONReadingFuckNSNulls than (1UL << 3). If Apple adds a reading option il will most probably be (1UL << 3) but it might not be Fuck NSNulls.

@nimrodbens
Copy link

nimrodbens commented Sep 7, 2017

i love you. i first come about nsnull today and spent the last 5 hours trying to figure it out. eventually after i did i just searched google "fuck nsnull". thank you for this.

fuck nsnull

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment