mustache.java pass json string

java, json, mustache, mustache.php

Solution

I was able to find a solution to this!

One can create a HashMap out of the json string and pass it to the mustache.execute method.

//create map using gson    
Map<String,Object> gsonMap = new HashMap<String,Object>();
gsonMap = (Map<String,Object>) gson.fromJson(myJsonString, gsonMap.getClass());

//pass the hashmap instead of a class object
mustache.execute(new BufferedWriter(new FileWriter(objFile)), gsonMap).flush();

Problem

I am using mustache.java and wish to plug the json string instead of an object. I am not sure why no one faced this issue before. ``` // works since an 'Example' object is passed in mustache.execute(new BufferedWriter(new FileWriter(objFile)), new Example()).flush(); // does not work since a json object is passed in directly JSONObject jsonObject = new JSONObject("{\n" + " \"header\": \"Colors\",\n" + " \"items\": [\n" + " {\"name\": \"red\", \"first\": true, \"url\": \"#Red\"},\n" + " {\"name\": \"green\", \"link\": true, \"url\": \"#Green\"},\n" + " {\"name\": \"blue\", \"link\": true, \"url\": \"#Blue\"}\n" + " ],\n" + " \"empty\": false\n" + "}"); mustache.execute(new BufferedWriter(new FileWriter(objFile)), jsonObject).flush(); ``` Code here: https://github.com/spullara/mustache.java/blob/master/example/src/main/java/mustachejava/Example.java

Original source