我經常發現需要將由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