Freemarker Container to JSON

Kind of a random post, but at work we’ve been trying to find a good way to dump a Freemarker object to JSON. I finally found a nice solution online, but it wasn’t even described as having the ability to do what it does, and now I can’t find the source of it. Hopefully this will help someone else out in the future, and if this code looks familiar, please let me know where it’s from so I can cite the source properly.

The following code will take a Freemarker sequence, hash, or collection (or a mixture of all three) and dump the contents to the page as JSON. It may work with other Freemarker data types as well, but I have not tested it. It’s currently a macro, but I think it would be fairly easy to convert it to a function as well.

<#macro objectToJsonMacro object> 
<@compress single_line=true> 
    <#if object?is_hash || object?is_hash_ex> 
        <#assign first="true"> 
        { 
        <#list object?keys as key> 
            <#if first="false">,</#if> 
            <#assign value><@objectToJsonMacro object=object<key> /></#assign> 
            "${key}" : ${value?trim} 
            <#assign first="false"> 
        </#list> 
        } 
    <#elseif object?is_enumerable> 
        <#assign first="true"> 
        [ 
        <#list object as item> 
            <#if first="false">,</#if> 
            <#assign value><@objectToJsonMacro object=item /></#assign> 
            ${value?trim} 
            <#assign first="false"> 
        </#list> 
        ] 
    <#else> 
        "${object?trim}" 
    </#if> 
</@compress> 
</#macro> 
This entry was posted in Web Development and tagged , , , . Bookmark the permalink.

2 Responses to Freemarker Container to JSON

Leave a Reply

Your email address will not be published. Required fields are marked *