Freemarker parse a String as Json

大憨熊 提交于 2019-11-28 01:00:52

问题


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.



来源:https://stackoverflow.com/questions/13087436/freemarker-parse-a-string-as-json

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