Removing nulls from a JSON structure recursively

后端 未结 4 1997
忘了有多久
忘了有多久 2021-01-05 22:46

I\'m frequently finding the need to cache data structures created by NSJSONSerialization to disk and as -writeToFile fails if there are nulls, I ne

4条回答
  •  一向
    一向 (楼主)
    2021-01-05 23:44

    + (id)getObjectWithoutNullsForObject:(id)object
    {
        id objectWithoutNulls;
    
        if ([object isKindOfClass:[NSDictionary class]])
        {
            NSMutableDictionary *dictionary = ((NSDictionary *)object).mutableCopy;
    
            [dictionary removeObjectsForKeys:[dictionary allKeysForObject:[NSNull null]]];
    
            for (NSString *key in dictionary.allKeys)
            {
                dictionary[key] = [self getObjectWithoutNullsForObject:dictionary[key]];
            }
    
            objectWithoutNulls = dictionary;
        }
        else if ([object isKindOfClass:[NSArray class]])
        {
            NSMutableArray *array = ((NSArray *)object).mutableCopy;
    
            [array removeObject:[NSNull null]];
    
            for (NSUInteger index = 0; index < array.count; index++)
            {
                array[index] = [self getObjectWithoutNullsForObject:array[index]];
            }
    
            objectWithoutNulls = array;
        }
        else if ([object isKindOfClass:[NSNull class]])
        {
            objectWithoutNulls = Nil;
        }
        else
        {
            objectWithoutNulls = object;
        }
    
        return objectWithoutNulls;
    }
    

提交回复
热议问题