2016-10-19 1 views
1

J'utilise moustache.java et souhaite boucher la chaîne json au lieu d'un objet. Je ne sais pas pourquoi personne n'a fait face à ce problème auparavant.moustache.java pass json string

// 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

ici: https://github.com/spullara/mustache.java/blob/master/example/src/main/java/mustachejava/Example.java

Répondre

1

j'ai pu trouver une solution à cela!

Vous pouvez créer un HashMap hors de la chaîne json et le passer à la méthode moustache.execute.

//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();