Freemark模板引擎定义Json对象

   最近我在做接口管理这一块,需要以Json的样式响应服务器,之前是通过将属性通过Map对象封装起来,然后将Map对象转换成Json对象,但这样实现起来代码量太大,并且不易扩展,后来看到了Freemark模板引擎,发现可以通过模板语言来解决这一问题,所以就记录下来,以便日后翻阅:
        //通过模板生成成功响应结果
        logger.info("通过模板生成响应结果。。。。。。。");
        //模板所放路径
        String path = "F:/workproject/opps-policy-center/policy-center-webapp/src/main/resources/template";
      
        //模板名称
        String templateName = "query_policy_success.flt";
        //通过Map对象保存数据源

        Map<String,Object> dataMap = new HashMap<String,Object>();
        dataMap.put("policyList", policyList);
        String json;
try {
json = FreeMarkerUtil.getStrByTemplate(path, templateName, dataMap);
logger.info("通过模板生成的成功响应结果为:"+json);
return json;
} catch (Exception e) {
logger.info(e.getMessage());
e.printStackTrace();
}


FreeMarkerUtil类:
package com.modules.util;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import java.io.File;
import java.io.StringWriter;

import java.util.Map;
import org.slf4j.Logger;

public class FreeMarkerUtil
{
   private static Logger log = Log.get();
   private static Configuration cfg;

   public static String getStrByTemplate(String path, String templateName, Map<String, Object> dataMap)
    throws Exception
  {
    try
    {
      if (cfg == null) {
         cfg = new Configuration();
       cfg.setDefaultEncoding("UTF-8");
       cfg.setDirectoryForTemplateLoading(new File(path));
     cfg.setObjectWrapper(new DefaultObjectWrapper());
       }
       Template t = cfg.getTemplate(templateName);
      StringWriter sw = new StringWriter();
      t.process(dataMap, sw);
      return sw.toString();
     } catch (Exception e) {
      e.printStackTrace();
       Log.error(log, e, "freemark文件解析异常,文件路径{},文件名{}", new Object[] { path, templateName });
      throw new Exception();
     }
   }
}
 
flt模板定义:
     {
    "result": "SUCCESS",
    "errMsg": "",
    "policyList": {
       <#list policyList as policy>
        "policy": [
            {
                "policyLevel":${policy.policyLevel!},
                "policyId":${policy.policyId!},
                "policySource":${policy.policySource!},
                "productType":${policy.productType!},
                "flightCode":${policy.flightCode!},
                "deptCode":${policy.deptCode!},
                "arrCode":${policy.arrCode!},
                "policyType":${policy.policyType!},
                "passengerType":${policy.passengerType!},
                "flightLimitType":${policy.flightLimitType!},
                "flightLimitNum":${policy.flightLimitNum!},
                "dayCondition":${policy.dayCondition!},
                "cabin":${policy.cabin!},
                "viewPrice":${policy.viewPrice!},
                "returnPoint":${policy.returnPoint!},
                "transactionFee":${policy.transactionFee!},
                "startTravelDate":${policy.startTravelDate!},
                "endTravelDate":${policy.endTravelDate!},
                "startTicketDate":${policy.startTicketDate!},
                "endTicketDate":${policy.endTicketDate!},
                "earliestBeforeValidDay":${policy.earliestBeforeValidDay!},
                "beforeValidDay":${policy.beforeValidDay!},
                "startIssueTicketWorkTime ":${policy.startCancelTicketWorkTime!},
                "endIssueTicketWorkTime":${policy.endCancelTicketWorkTime!},
                "startCancelTicketWorkTime ":${policy.startCancelTicketWorkTime!},
                "endCancelTicketWorkTime ":${policy.endCancelTicketWorkTime!},
                "standardizedTP ":${policy.standardizedTP!},
                "standardizedGQ ":${policy.standardizedGQ!},
                "standardizedQZ ":${policy.standardizedQZ!},
                "updateTime":${policy.updateTime!},
                "switchPnr":${policy.switchPnr!},
                "ticketEff":${policy.ticketEff!},
                "officeId":${policy.officeId!},
                "comment":${policy.comment!}
            },
        ]
        </#list>
    }

}

        

你可能感兴趣的:(freemark)