Freemarker parse a String as Json

陌路散爱 提交于 2019-11-29 07:41:33

Use ?eval. It works because JSON maps happen to be valid FreeMarker expressions (update: except that null is not recognized in FreeMarker 2.3.x).

<#assign test = "{\"foo\":\"bar\", \"f\":4, \"text\":\"bla bla\"}">
<#assign m = test?eval>

${m.foo}  <#-- prints: bar -->

<#-- Dump the whole map: -->
<#list m?keys as k>
  ${k} => ${m[k]}
</#list>

(BTW, you don't have to use \" if you quote the string with ' instead of ".)

freemarker.sourceforge.net/docs/pgui_datamodel_method.html

in code:

// a class to parse Json, just add this method to your rendered template data
// with data.put("JsonParser", new FreemarkerJsonParser()); 
// or in shared variables http://freemarker.sourceforge.net/docs/pgui_config_sharedvariables.html
public class FreemarkerJsonParser implements TemplateMethodModel{
    @Override
    public Object exec(List args) throws TemplateModelException {
        return new Gson().fromJson(s, new TypeToken<Map<String, String>>() {}.getType());((String) args.get(0));
    }
}

in the template:

<#assign map = JsonParser("{\"foo\":\"bar\", \"f\":4, \"text\":\"bla bla\"}")>
${map.text}

Sounds like you need to define/implement a template that reads JSON.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!