我经常发现需要将由NSJSONSerialization
创建的数据结构缓存到磁盘,并且如果-writeToFile
失败(如果有空值),我需要一个在未知结构时工作的修复程序。 这是有效的,并且允许直接变异,因为NSMutableDictionary本身的实例本身没有被枚举,但它感觉有点不好意思。以递归方式从JSON结构中删除空值
这是完全好还是绝对有必要重新创建一棵树并返回?
- (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:[NSNull空])尝试这样 – 2013-05-01 04:51:34
是origionally它与'isKindOfClass'测试,但在类似的规定太问题有关消除空值(我似乎无法找到),比较指针常量更有效。 – TijuanaKez 2013-05-01 04:55:17
我做了一个类别。你可以在这里找到它https://github.com/bismasaeed00/NullReplacer – bisma 2017-04-21 07:11:36