Search code examples
iosobjective-ccastingnsdictionarynsmutabledictionary

Change a dictionary's all value to string


I want to change the Dictionary's all value to String, how to do with it?

Such as:

{   @"a":"a", 
    @"b":2, 
    @"c":{
      @"c1":3,
      @"c2":4
    }
}

I want convert to :

{   @"a":"a", 
    @"b":"2", 
    @"c":{
      @"c1":"3",
      @"c2":"4"
    }
}

How to do with it? I think all the day.

If I use below method to traverse the dictionary values:

NSArray *valueList = [dictionary allValues];

for (NSString * value in valueList) {
    // change the value to String
}

If the value is a dictionary, how about it?

So, someone can help with that?


Solution

  • You could do this with a recursive method, it changes all NSNumber values to NSString and calls itself for nested dictionaries. Since a dictionary cannot be mutated while being enumerated a new dictionary is created and populated:

    - (void)changeValuesOf:(NSDictionary *)dictionary result:(NSMutableDictionary *)result
    {
        for (NSString *key in dictionary) {
            id value = dictionary[key];
            if ([value isKindOfClass: [NSDictionary class]]) {
                NSMutableDictionary * subDict = [NSMutableDictionary dictionary];
                result[key] = subDict;
                [self changeValuesOf:value result:subDict];
            } else if ([value isKindOfClass: [NSNumber class]]) {
                result[key] = [NSString stringWithFormat:@"%@", value];
            } else {
                result[key] = value;
            }
        }
    }
    
    NSDictionary *dictionary = @{@"a": @"a", @ "b":@2, @"c": @{@"c1": @3,  @"c2":@4 }};
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    [self changeValuesOf:dictionary result:result];
    NSLog(@"%@", result);