I'm frequently finding the need to cache data structures created by NSJSONSerialization
to disk and as -writeToFile
fails if there are nulls, I need a fix that works when the structure is unknown.
This works, and direct mutation is allowed as the instances of NSMutableDictionary themselves are not being enumerated, but it feels a bit hacky.
Is this totally fine or is it absolutely necessary to recreate a new tree and return that?
- (void) removeNullsFromJSONTree:(id) branch
{
if ([branch isKindOfClass:[NSMutableArray class]])
{
//Keep drilling to find the leaf dictionaries
for (id childBranch in branch)
{
[self removeNullsFromJSONTree:childBranch];
}
}
else if ([branch isKindOfClass:[NSMutableDictionary class]])
{
const id nul = [NSNull null];
const NSString *empty = @"";
for(NSString *key in [branch allKeys])
{
const id object = [branch objectForKey:key];
if(object == nul)
{
[branch setObject:empty forKey:key];
}
}
}
}
isKindOfClass
but as stated in similar SO question about removing nulls (which i can't seem to find), comparing pointers to constants is more efficient. – Kaseykasha