且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Freemarker将String解析为Json

更新时间:2022-11-09 10:15:32

使用?eval.之所以起作用,是因为JSON映射恰好是有效的FreeMarker表达式(更新:在FreeMarker 2.3.x中无法识别null除外).

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