Peter T.
Peter T.

Reputation: 3325

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?

Upvotes: 2

Views: 20249

Answers (5)

RiZKiT
RiZKiT

Reputation: 2531

I found this gist: https://gist.github.com/ruudud/698035f96e860ef85d3f

It offers two versions (one simple, one extended) of an objectToJson freemarker macro.

The usage is as follows (but also explained in the gist):

<#assign foo><@objectToJson object=data.myobject /></#assign>
<pre>${foo}</pre>
<script>console.log(${foo});</script>

Upvotes: 2

dpolivaev
dpolivaev

Reputation: 558

You can create a configuration and set your ObjectMapper instance as follows:

Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);
try {
  cfg.setSharedVariable("JSON",
    configuration.getObjectWrapper().wrap(new ObjectMapper()));
} catch (TemplateModelException e) {
    throw new RuntimeException(e);
}
 

Templates created with this configuration can access it as follows to render your object:

{
  "yourObjectPropertyName": ${JSON.writeValueAsString(yourObject)}
}

Upvotes: 2

Peter T.
Peter T.

Reputation: 3325

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

Upvotes: 1

Nachiketha
Nachiketha

Reputation: 23575

<script>
    /* inside script tag assign js variable with Java Obj values */
    var JSObj = {};
    <#assign JavaObj = model["JavaObj"]>
    JSObj.value1 = ${JavaObj.val1};
    JSObj.value2 = ${JavaObj.val2};
    /*OR alternatively one can use FTL interator to assign large Java List etc */

   /* Once transferred to client side use the JSON.stringify(YOUR_OBJECT, null, '\t');  kind of function to display in UI  */

</script>

Upvotes: 0

ddekany
ddekany

Reputation: 31162

There's no such functionality built in. (Of course, you could use some external library that does that, like Gson maybe, and call it from the template.)

Upvotes: 1

Related Questions