一、依赖
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.32</version>
</dependency>
二、工具类
package com.chenwc.freemarker.util;
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* 模板引擎 FreeMarker
*
* @author chenwc
* @date 2023/3/14 21:13
*/
public class FreemarkerUtil {
/**
* 根据模板,利用提供的数据,生成文件
*
* @param ftlFilePath 模板文件
* @param data 数据
* @param outFilePath 最终生成的文件
* @return 生成文件的内容
*/
public static String execute(String ftlFilePath, Map<String, Object> data, String outFilePath) {
//创建Freemarker配置实例
Configuration cfg = new Configuration(Configuration.VERSION_2_3_32);
//截取模板文件路径
int i = ftlFilePath.lastIndexOf("/") == -1 ? ftlFilePath.lastIndexOf("\\")
: ftlFilePath.lastIndexOf("/");
try {
cfg.setDirectoryForTemplateLoading(new File(ftlFilePath.substring(0, i + 1)));
cfg.setDefaultEncoding(String.valueOf(StandardCharsets.UTF_8));
//加载模板文件
Template t1 = cfg.getTemplate(ftlFilePath.substring(i + 1));
Writer out = new FileWriter(outFilePath);
t1.process(data, out);
out.flush();
out.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
return readFile(outFilePath);
}
/**
* 通过字节流读取文件
*
* @param path 读取文件路径
* @return 文件内容
*/
public static String readFile(String path) {
byte[] result;
File file = new File(path);
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
int available = fis.available();
if (available <= 0) {
return null;
}
result = new byte[available];
fis.read(result);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
// 在finally语句块当中确保流一定关闭。
try {
if (null != fis) {
fis.close();
}
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
return new String(result, StandardCharsets.UTF_8);
}
}
三、测试
1、Main.java
package com.chenwc.freemarker;
import com.alibaba.fastjson.JSONObject;
import com.chenwc.freemarker.util.FreemarkerUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
/**
* @author chenwc
* @date 2023/3/14 21:21
*/
public class Main {
private static final Logger log = LoggerFactory.getLogger(Main.class);
private static final String basePath = "E:\\IdeaProjects_Workspace\\freemarker\\src\\main\\resources\\template\\";
public static void main(String[] args){
String ftlFilePath = basePath + "\\gys_inte.json.ftl";
String outFilePath = basePath + "\\output.json";
String inputFilePath = basePath + "\\input.json";
JSONObject inputJson = JSONObject.parseObject(FreemarkerUtil.readFile(inputFilePath));
log.info(inputJson.toJSONString());
Map<String, Object> data = new HashMap<>();
data.put("puuid", inputJson.getJSONObject("esb").getJSONObject("data").getJSONObject("datainfos").getString("puuid"));
data.put("syncode", inputJson.getJSONObject("esb").getJSONObject("data").getJSONObject("datainfos").getString("syncode"));
data.put("datainfos", inputJson.getJSONObject("esb").getJSONObject("data").getJSONObject("datainfos").getJSONArray("datainfo"));
Map<String, Object> map = new HashMap<>();
map.put("data", data);
JSONObject resultJson = JSONObject.parseObject(FreemarkerUtil.execute(ftlFilePath, map, outFilePath));
log.info(resultJson.toJSONString());
}
}
2、ftl 模板
{
"esb": {
"data" : {
"datainfos":{
<#if data.puuid??>
"puuid" : "${data.puuid}",
</#if>
<#if data.syncode??>
"syncode" : "${data.syncode}",
</#if>
<#if data.datainfos?? && data.datainfos?size gt 0 >
"datainfo" : [
<#list data.datainfos as datainfo>
{
"supplier_code":"<#if datainfo.code??>${datainfo.code?json_string!}</#if>",
"supplier_name":"<#if datainfo.desc1??>${datainfo.desc1?json_string!}<#else></#if>",
"supplier_domestic_foreign":"<#if datainfo.desc2??>${datainfo.desc2?json_string!}<#else></#if>",
"supplier_type":"<#if datainfo.desc3??>${datainfo.desc3?json_string!}<#else></#if>",
"supplier_enterprise_nature_lv1":"<#if datainfo.desc15??>${datainfo.desc15?json_string!}<#else></#if>",
"supplier_enterprise_nature_lv2":"<#if datainfo.desc34??>${datainfo.desc34?json_string!}<#else></#if>",
"supplier_enterprise_nature_lv3":"<#if datainfo.desc33??>${datainfo.desc33?json_string!}<#else></#if>",
"supplier_enterprise_nature":"<#if datainfo.desc4??>${datainfo.desc4?json_string!}<#else></#if>",
"supplier_dunbar_code":"<#if datainfo.desc5??>${datainfo.desc5?json_string!}<#else></#if>",
<#if "${datainfo.desc2?json_string!}"=="境内" && "${datainfo.desc35?json_string!}"=="企业">
"supplier_registered_address":"<#if datainfo.desc6??>${datainfo.desc6?json_string!}<#else></#if>",
"supplier_registered_currency":"<#if datainfo.desc11??>${datainfo.desc11?json_string!}<#else></#if>",
"supplier_registered_code":"<#if datainfo.desc28??>${datainfo.desc28?json_string!}<#else></#if>",
"supplier_registered_capital":"<#if datainfo.desc13??>${datainfo.desc13?json_string!}<#else></#if>",
"supplier_province_state":"<#if datainfo.desc9??>${datainfo.desc9?json_string!}<#else></#if>",
"supplier_city":"<#if datainfo.desc10??>${datainfo.desc10?json_string!}<#else></#if>",
"supplier_province_code":"<#if datainfo.desc29??>${datainfo.desc29?json_string!}<#else></#if>",
"supplier_city_code":"<#if datainfo.desc30??>${datainfo.desc30?json_string!}<#else></#if>",
<#else>
"supplier_registered_address":"",
"supplier_registered_currency":"",
"supplier_registered_code":"",
"supplier_registered_capital":"",
"supplier_province_state":"",
"supplier_city":"",
"supplier_province_code":"",
"supplier_city_code":"",
</#if>
"supplier_country_code":"<#if datainfo.desc7??>${datainfo.desc7?json_string!}<#else></#if>",
"supplier_country_name":"<#if datainfo.desc8??>${datainfo.desc8?json_string!}<#else></#if>",
"supplier_credit_code":"<#if datainfo.desc12??>${datainfo.desc12?json_string!}<#else></#if>",
"supplier_legal_person":"<#if datainfo.desc14??>${datainfo.desc14?json_string!}<#else></#if>",
"supplier_source_system":"<#if datainfo.desc18??>${datainfo.desc18?json_string!}<#else></#if>",
"supplier_id_no":"<#if datainfo.desc19??>${datainfo.desc19?json_string!}<#else></#if>",
"supplier_cmei_message":"<#if datainfo.desc20??>${datainfo.desc20?json_string!}<#else></#if>",
"supplier_dzzb_id":"<#if datainfo.desc21??>${datainfo.desc21?json_string!}<#else></#if>",
"supplier_is_valid":"<#if datainfo.desc22??>${datainfo.desc22?json_string!}<#else></#if>",
"enterprise_nature_code":"<#if datainfo.desc32??>${datainfo.desc32?json_string!}<#else></#if>",
"supplier_post_symbol":"<#if datainfo.desc27??>${datainfo.desc27?json_string!}<#else></#if>",
"enterpriseIndividual":"<#if datainfo.desc35??>${datainfo.desc35?json_string!}<#else></#if>",
"uuid":"<#if datainfo.uuid??>${datainfo.uuid?json_string!}</#if>"
}
<#if datainfo_has_next>,</#if>
</#list>
]
}
</#if>
},
"desc":"SUCCESS",
"result":"S"
}
}
3、input.json
{
"esb": {
"data": {
"datainfos": {
"datainfo": [
{
"code": "10314031",
"desc30": "110000",
"uuid": "DADB06AFCCF74336AAA945046BF01AF0",
"desc19": "",
"desc18": "ejdw_wy_cdh",
"desc11": "人民币",
"desc33": "社会团体",
"desc10": "北京市",
"desc32": "020201",
"desc13": "20000000.00",
"desc35": "企业",
"desc12": "51100000500005246D",
"desc34": "非营利法人",
"desc15": "法人",
"desc14": "毛予锋",
"desc20": "",
"desc1": "中国机床工具工业协会-测试",
"desc2": "境内",
"desc29": "110000",
"desc3": "外部",
"desc4": "社团",
"desc5": "-",
"desc6": "北京市西城区莲花池东路102号天莲大厦12层",
"desc7": "156",
"desc8": "中华人民共和国",
"desc9": "北京市",
"desc22": "A",
"desc21": "",
"desc28": "CNY",
"desc27": "元"
}
],
"syncode": "gys_to_integrate",
"puuid": "D773D3C147BA4838BEC3F69C422A2A3F"
}
}
}
}
4、output.json
{
"esb": {
"result": "S",
"data": {
"datainfos": {
"datainfo": [
{
"supplier_province_code": "110000",
"supplier_city": "北京市",
"supplier_type": "外部",
"supplier_country_code": "156",
"uuid": "DADB06AFCCF74336AAA945046BF01AF0",
"supplier_city_code": "110000",
"supplier_dunbar_code": "-",
"supplier_enterprise_nature_lv3": "社会团体",
"supplier_registered_currency": "人民币",
"supplier_enterprise_nature": "社团",
"supplier_enterprise_nature_lv2": "非营利法人",
"supplier_enterprise_nature_lv1": "法人",
"supplier_legal_person": "毛予锋",
"supplier_name": "中国机床工具工业协会-测试",
"supplier_post_symbol": "元",
"enterpriseIndividual": "企业",
"supplier_registered_address": "北京市西城区莲花池东路102号天莲大厦12层",
"supplier_dzzb_id": "",
"supplier_registered_code": "CNY",
"supplier_credit_code": "51100000500005246D",
"supplier_domestic_foreign": "境内",
"supplier_country_name": "中华人民共和国",
"supplier_source_system": "ejdw_wy_cdh",
"supplier_is_valid": "A",
"supplier_province_state": "北京市",
"supplier_id_no": "",
"enterprise_nature_code": "020201",
"supplier_cmei_message": "",
"supplier_code": "10314031",
"supplier_registered_capital": "20000000.00"
}
],
"syncode": "gys_to_integrate",
"puuid": "D773D3C147BA4838BEC3F69C422A2A3F"
}
},
"desc": "SUCCESS"
}
}