Search code examples
jsonfreemarker

What is the easiest way to render a freemarker object as JSON?


I have a data structure in freemarker which I would like to render as JSON notation in the output, similar to Javascript's JSON.stringify, is there something in freemarker such as object?json or any other simple way?


Solution

  • We wrote a simple pseudo DataLoader for FreeMarker that returns an "JSON" object that provides the methodes stringify() and parse():

    package de.teambits.server.fmpp;
    
    import flexjson.JSONDeserializer;
    import flexjson.JSONSerializer;
    import fmpp.Engine;
    import fmpp.tdd.DataLoader;
    
    import java.util.List;
    
    /**
     * Returns a JSON object that offers parse() and stringify() methods for use in fmpp
     */
    public class JSONFactory implements DataLoader {
    
        @Override
        public Object load(Engine e, List args) throws Exception {
            return new JSON();
        }
    
        public static class JSON {
            public String stringify(Object object) {
                return new JSONSerializer().deepSerialize(object);
            }
    
            public Object parse(String jsonString) {
                return new JSONDeserializer().deserialize(jsonString);
            }
        }
    }
    

    So, if you add to your Freemarker / fmpp config this JSON object:

    data: {
        JSON: de.teambits.server.fmpp.JSONFactory()
    }
    

    You can simple call ${ JSON.stringify(object) } or ${ JSON.parse("json-string") }