将字典的所有值更改为字符串

Change a dictionary's all value to string

我想把Dictionary的all值改成String,怎么办?

如:

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

我想转换为:

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

怎么办?我整天都在想。

如果我使用下面的方法遍历字典值:

NSArray *valueList = [dictionary allValues];

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

如果值是一个字典,怎么样?

那么,有人可以帮忙吗?

您可以为字典创建类别并添加类似 stringValueForKey: 的方法。 实现可以是这样的:

- (NSString)stringValueForKey:(NSString*)key
{
   id value = self[key];
   if( [value respondsToSelector:@selector(stringValue)])
       return [value performSelector:@selector(stringValue)]
   return nil;
}

您可以使用递归方法执行此操作,它将所有 NSNumber 值更改为 NSString 并为嵌套字典调用自身。由于在枚举时无法更改字典,因此创建并填充了新字典​​:

- (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);