快捷搜索: 王者荣耀 脱发

FreemarkerUtils读取JSON数据

Freemarker读取JSON数据

    需要maven依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
    读取模板数据返回字符串
@Autowired
Configuration configuration;

//模板中不可出现‘’等特殊字符
public String generateContent(String templateName, Object param) {
        if (StringUtils.isEmpty(templateName) || param == null) {
            new RunException("模板名称不能为空");
        }
        try {
            configuration.setClassForTemplateLoading(FreeMarkerConfigurer.class, basePackagePath);
            Template template = configuration.getTemplate(templateName, "utf-8");
            return FreeMarkerTemplateUtils.processTemplateIntoString(template, param);
        } catch (Exception e) {
            new RunException("读取模板错误");
        }
        return null;
    }
    ftl模板内容
{
    "key": "37",
    "year_x" : "2097",
    "year_y" : "1295",
    "month_x" : "2215",
    "month_y" : "1295",
    "day_x" : "2282",
    "day_y" : "1295",
    "formal_path" : "/dev/ioffice/file/YYZZ_KLSZ.png",
    "final_path" : "/dev/ioffice/file/ZH_CWL_YYZZ_KLSZ.png"
}
    将模板数据转换为JSONObject对象
String json = this.generateContent("模板路径+模板名称"+".ftl", null);
JSONObject JSONObj = JSONObject.parseObject(json);
String objValue = JSONObj.getString("key");
经验分享 程序员 微信小程序 职场和发展