2

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.

Reddy
  • 8,737
  • 11
  • 55
  • 73
cloudpre
  • 1,001
  • 2
  • 15
  • 28
  • 1
    I take it you already looked at https://github.com/spullara/mustache.java -- The java implementation of mustache.js by Sam Pullara? – Tom McClure Oct 20 '12 at 03:00

3 Answers3

2

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.

ebaxt
  • 8,287
  • 1
  • 34
  • 36
0

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

rich
  • 18,987
  • 11
  • 75
  • 101
0

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.

Community
  • 1
  • 1
Tom McClure
  • 6,699
  • 1
  • 21
  • 21