我经常发现需要将创建的数据结构缓存NSJSONSerialization
到磁盘,-writeToFile
如果有空值会失败,我需要一个在结构未知时有效的修复程序。这是可行的,并且允许直接变异,因为 NSMutableDictionary 本身的实例没有被枚举,但感觉有点 hacky。
这完全没问题还是绝对有必要重新创建一棵新树并返回它?
- (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];
}
}
}
}