有一个模板,例如:
亲爱的用户${name},你好,上次登录时间为${time}
要把这个模板中的变量替换为实际值,参数为一个json串,
{"name":11,"time":2014-10-21}
用java 如何实现呢?
static final String jsonStr = "{\"name\":\"11\",\"time\":\"2014-10-21\"}";
static final String template = "亲爱的用户${name},你好,上次登录时间为${time}";
static String generateWelcome(String jsonStr,String template){
Gson gson = new Gson();
HashMap jsonMap = gson.fromJson(jsonStr, HashMap.class);
for (Object s : jsonMap.keySet()) {
template = template.replaceAll("\\$\\{".concat(s.toString()).concat("\\}")
, jsonMap.get(s.toString()).toString());
}
return template;
}
public static void main(String[] args) throws IOException {
System.out.println(generateWelcome(jsonStr,template));
}
需要Gson:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
</dependency>
如果自己实现大概要这么搞吧
- 把
JSON
转成map
- 遍历
keys
str.replace("${" + key + "}", map.get(key));
如果是复杂的内容直接可以上模板组件了 不过一句话用velocity有点不值 话说这么简单的东西字符串拼接都做的出来,,