Take the 2-minute tour ×

My application allows users to define few templates for text etc. Eg: one of the shortcuts could be hi {{name}}, nice to meet you.

I have a complex json which has name and lot of inner jsons. I am looking for a good mustache kind of implementation in java which can replace the values of json into the string. Currently I am iterating through each key and replacing the string but I am looking for more elegant solution which gives the users more power in their templating like loops, conditions etc similar to mustache/handlebars.

Though mustache for java looks good, I haven't seen any implementation which can replace with a JSON. All examples applies on an object but not on a json object. Looks to me that internally, it uses an object mapper to convert an object to object and somehow it applies that.

Perhaps I can convert JSON into a map and provide it.

Probably I am missing something. Thanks.

share|improve this question
I take it you already looked at github.com/spullara/mustache.java -- The java implementation of mustache.js by Sam Pullara? –  Tom McClure Oct 20 '12 at 3:00

3 Answers 3

up vote 2 down vote accepted

You have to convert the JSON string to a Java object. You can use a nested Map, Multimap or create you own object to represent the structure.

You probably want to use a JSON-serializer to create a java object from the JSON-string. Good solutions are Jackson, Gson or Json-simple.

Once you have a correct Java representation of the JSON, you can use a template engine to do the string replacement. Known libraries are Freemarker, Velocity and StringTemplate

Personally I recommend Jackson+Freemarker, but all are good solutions.

share|improve this answer

Try Apache Velocity it does something very similar for property substitution in text.

share|improve this answer

Chunk is a very JSON-friendly template engine. Loops & conditions, tag syntax is similar to Mustache, and you can reference nested associative arrays of data fairly elegantly right from the template.

See sample code for JSON + Chunk in this answer.

share|improve this answer

Your Answer


