工作中要用到個別字段動態變化的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
}