如何在java中使用StrSubstitutor嵌套Map

时间:2014-05-12 12:03:24

标签: java map

    Map<String, Object> baseMap = new HashMap<String, Object>();

    baseMap.put("Name", "Raja");

    Map<String, Object> address = new HashMap<String, Object>();
    address.put("Street", "RAMA");

    baseMap.put("Address", address);

    StrSubstitutor strsub = new StrSubstitutor(baseMap);

    String str = "This is ${Name} from ${Address.Street}";

    System.out.println(strsub.replace(str));

输出是:

这是来自$ {Address.Street}的Raja

我需要的是:

这是来自RAMA的Raja

我怎么能得到这个?

1 个答案:

答案 0 :(得分:2)

可能您需要另一个StrSubstitutor实例,它取代了address

StrSubstitutor strsub = new StrSubstitutor(baseMap);
StrSubstitutor baseSub = new StrSubstitutor(address);

String str = "This is ${Name} from ${Address.Street}";

System.out.println(baseSub.replace(strsub.replace(str)));

但我认为更好的解决方案是使用sinlge baseMap

Map<String, Object> baseMap = new HashMap<String, Object>();

baseMap.put("Name", "Raja");
baseMap.put("Street", "RAMA");

StrSubstitutor strsub = new StrSubstitutor(baseMap);

String str = "This is ${Name} from ${Address.Street}";

System.out.println(strsub.replace(str));