Looking for a template engine which supports JsonPath (Java)



I’m developing a microservice (let’s call it email microservice) which generates emails from HTML templates. Basically, the client sends a json with some data to the email microservice, and based on that data it has to generate an email (populate fields in html template with values coming in the json). The client is our other microservice, which prepares json and sends to the email microservice.

Json structure would be something like this:

{
   "data":{
      ......
   },
   .......
}
 

“Data” is the dynamic object which can contain different things. So we can populate it with pairs key – value, for example, and then map to HashMap and then use this HashMap to populate our template, using some template engine (Velocity, thymeleaf or something else). Let’s say we can prepare json like this:

{
   "data":{
      "userName":"Jack"
   },
   .......
}
 

And then use it in the template, something like this:

<b> Hello {{userName}}! </b>

This approach works fine, but I would like to simplify it, so we wouldn’t need to prepare a proper json everytime (populate “data” field with key – value pairs), instead we would like just to put there some POJOs, without carrying which fields we need, and then use JsonPath in our templates to access required data. For example we create a json:

{
   "data":{
      "user": {
          "firstName":"Jack",
          ..........
      },
      ...........
   },
   .......
}
 

And in the template write something like that:

<b> Hello {{data.user.firstName}}! </b>

That would save us some time, cause we wouldn’t need to cary about json structure. Is there any template engine which can use a Json as input and access values by JsonPath? So I write something like this: data.user.firstName and the engine automatically finds value from the given json.

Answer

The problem was solved by using Velocity and JsonPath lib.

I’ve created a new tool for Velocity:

public class JsonPathTool {

    private final String json;

    public JsonPathTool(String json) {
        this.json = json;
    }

    public Object valueAt(String jsonPath) {

        jsonPath = "$." + jsonPath;                     
        return JsonPath.read(this.json, jsonPath);            
    }
}

Then I put JsonPathTool in Velocity context:

VelocityContext ctx = new VelocityContext();
JsonPathTool jsonPathTool = new JsonPathTool(json);
ctx.put("data", jsonPathTool);

And in my templates I use following syntax:

"<b> Hello $data.valueAt("user.firstName") </b>"


Source: stackoverflow