Java Map填充Json模版,并生成Json文件
一、准备工作
- 引入基础的springboot环境
- 引入freemark依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
- 创建json模版
{
"parameter":{
"username":"${readerUsername}",
"password":"${readerPassword}"
}
}
二、创建读取模版工具类
package com.luwang.data.datax.util;
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;
}
}
三、根据模版生成Json文件
@Test
void myDeliver3() throws Exception {
// 该文件在resources目录下
String filePath = "/job/JobModel.ftl";
FreeMarkerTemplateUtils utils = new FreeMarkerTemplateUtils();
HashMap<Object, Object> map = new HashMap<Object, Object>();
map.put("readerUsername","root");
map.put("readerPassword","Lqgs@2022");
map.put("writeUsername","Lqgs@2022");
map.put("writePassword","Lqgs@2022");
map.put("channel","2");
String content = utils.getData(filePath,map);
System.out.println(content);
FileWriter fileWriter = new FileWriter("D:\\JavaCode\\data-middle-platform\\data-datax\\datax\\job\\JobModel-2023-01.json");
fileWriter.write(content);
fileWriter.close();
}
分类:
工具
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?