Freemarker parse a String as Json

2019-04-09 07:25发布

问题:

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

回答1:

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



回答2:

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}


回答3:

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



标签: freemarker