2

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?

Peter T.
  • 2,927
  • 5
  • 33
  • 40
  • Why not sending it to client in JavaScript format and use client side rendering using : JSON.stringify(YOUR_OBJECT, null, '\t'); – Nachiketha Nov 20 '15 at 09:05
  • Is there a simple way of sending the object to the client as Javascript? Actually, I wouldn't care much if it's JSON or (a more relaxed representation of) Javascript. – Peter T. Nov 22 '15 at 11:29
  • Added one of the possible way to send object to client in answers section. – Nachiketha Nov 23 '15 at 11:30

4 Answers4

2

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)}
}
dpolivaev
  • 494
  • 3
  • 12
  • ah, interesting. That's cool that you mention this, because I ran into issues with my solution very recently although I did ask the years ago, so your suggestion comes in with perfect timing, wow! :-) – Peter T. Jun 28 '21 at 16:42
1

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

ddekany
  • 29,656
  • 4
  • 57
  • 64
1

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

Peter T.
  • 2,927
  • 5
  • 33
  • 40
0
<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>
Nachiketha
  • 21,705
  • 3
  • 24
  • 32
  • Ah, the idea is to create JS code from Freemarker. What I did in one case is to create the JSON explicitely { "value1": "${obj.val1}", "value2": ${obj.val2WhichIsAnInt} } - however, I was looking for a generic solution. – Peter T. Nov 23 '15 at 22:22