工作中要用到个别字段动态变化的json数据,想到了FreeMarker + 模板来实现的方法,但是百度了很多内容,本地实现之后都无法正常运行。所以研究了一天,才整理出来一份能运行成功的,记录一下:

一、代码,这里我写了一个类FreeMarkerTemplateUtils ,放在src/test/java/路径下就行:

package *******;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.StringWriter;
import java.util.HashMap;

public class FreeMarkerTemplateUtils {

public String getData(String filePath, HashMap<Object, Object> map) throws Exception {
StringWriter writer = new StringWriter();

//创建配置类
Configuration cfg = new Configuration(Configuration.getVersion());
// 设置类加载机制加载模板,这里可以参考http://freemarker.foofun.cn/pgui_config_templateloading.html的内容,这是用的第二种方法。
cfg.setClassForTemplateLoading(this.getClass(),"/");
// 设置字符集
cfg.setDefaultEncoding("UTF-8");

// 加载模板
Template template = cfg.getTemplate(filePath);
// 静态化内容
template.process(map,writer);
String content = writer.toString();

return content;
}
}

二、模板文件,deliverDemo.ftl,放在src/test/resources/路径下就行
{
"cityId": ${cityId},
"cityName": "测试城市名",
"cky2": 316,
"countryId": 0000
}

三、测试类,放在src/test/java/路径下就行。网上很多资料需要把测试类或者FreeMarkerTemplateUtils 类放到特定目录,这里不需要。
@Test
void myDeliver3() throws Exception {
String filePath = "deliverDemo.ftl";
FreeMarkerTemplateUtils utils = new FreeMarkerTemplateUtils();

HashMap<Object, Object> map = new HashMap<Object, Object>();
map.put("cityId",110);
String content = utils.getData(filePath,map);
System.out.println(content);
}
四、结果
{
"cityId": 110,
"cityName": "测试城市名",
"cky2": 316,
"countryId": 0000
}
posted on 2021-10-21 18:23  大荔秦川牛  阅读(1844)  评论(0编辑  收藏  举报