Freemarker parse a String as Json

2019-04-09 07:17发布

Probably it's not possible,
but I would like to transform a json string in a map with freemarker

ex:

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

and be able to get the text key from this string

标签: freemarker
3条回答
男人必须洒脱
2楼-- · 2019-04-09 07:26

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 ".)

查看更多
3楼-- · 2019-04-09 07:40

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}
查看更多
Summer. ? 凉城
4楼-- · 2019-04-09 07:45

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

查看更多
登录 后发表回答