Over a million developers have joined DZone.

Trimou Templates JSON Support

DZone's Guide to

Trimou Templates JSON Support

Free Resource

Since version 1.4.0 Trimou has a new extension which delivers some basic JSON support by means of google-gson APIs. In particular, the extension provides a special resolver that makes it easier to work with com.google.gson.JsonElement instances. The motivation is to allow the developer to use JSON data directly in a template with minimal additional effort. Basically if you have some JSON data (String, Reader, etc.), you can parse it with google-gson and then use the resulting JsonElement as a context object for your Trimou templates.

Let's have a look at some simple example...

Test data:

    "firstName": "Jan",
    "lastName": "Novy",
    "address": {
        "street": "Nova",
        "city": "Prague",
        "state": "CZ",
        "postalCode": "11000"
    "phoneNumbers": [
            "type": "home",
            "number": "+42002012345"
            "type": "mobile",
            "number": "+420728000111"


Last name: {{lastName}}
Street: {{address.street}}
Phone numbers: {{#phoneNumbers}}{{number}}{{#iterHasNext}}, {{/iterHasNext}}{{/phoneNumbers}}
Type of the first phone number: {{phoneNumbers.0.type}}
Type of the second phone number: {{phoneNumbers.1.type}}

Java code:

// Load and parse the test data
JsonElement jsonElement = new JsonParser().parse(...);
// Build engine - JsonElementResolver is loaded automatically
MustacheEngine engine = MustacheEngineBuilder
                             .addTemplateLocator(new ServletContextTemplateLocator(10, "/WEB-INF/templates"))

// Get the template
Mustache mustache = engine.getMustache("json_test.mustache");

// Render the template
String output = mustache.render(jsonElement);

Expected result:

Last name: Novy
Street: Nova
Phone numbers: +42002012345, +420728000111
Type of the first phone number: home
Type of the second phone number: mobile

Let's sum up JsonElementResolver features:

  • allows you to access com.google.gson.JsonObject properties via dot notation; e.g. if "foo" is resolved as a JsonObject instance then "foo.bar" is translated to "foo.get("bar")"
  • automatically unwraps com.google.gson.JsonPrimitive;  e.g. if "foo" is resolved as a JsonPrimitive instance and contains a boolean value then "foo" is translated to "foo.getAsBoolean()"
  • com.google.gson.JsonArray elements can be accessed via index; e.g. if "foo" is resolved as a JsonArray instance then "foo.1" is translated to "foo.get(1)")
  • handles JsonNull instances

If you want to know more visit the Trimou homepage and project documentation!


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}