2013-03-21 13 views
5

Sto usando questo codice qui sotto per unire i dati JSON in un modello, per ottenere HTML:Prendere Baffi Template, passare JSON e Convertire in HTML

Template:

String schema = "<h1>{{header}}</h1>" 
    + "{{#bug}}{{/bug}}" 
    + "{{#items}}" 
    + "{{#first}}" 
    + "<li><strong>{{title}}</strong> 
    + </li>" 
    + "{{/first}}" 
    + "{{#link}}" 
    + "<li><a href=\"{{url}}\">{{name}} 
    + </a></li>" 
    + "{{/link}}" 
    + "{{/items}}" 
    + "{{#empty}}" 
    + "<p>The list is empty.</p>" 
    + "{{/empty}}"; 

JSON oggetto:

try { 
    String template = "{\"header\": \"Colors\", " 
     + "\"items\": [ " 
     + "{\"name\": \"red\", \"first\": true, \"url\": \"#Red\"}, " 
     + "{\"name\": \"green\", \"link\": true, \"url\": \"#Green\"}, " 
     + "{\"name\": \"blue\", \"link\": true, \"url\": \"#Blue\"}" 
     + " ], \"empty\": false }"; 

    JSONObject jsonWithArrayInIt = new JSONObject(template); 
    JSONArray items = jsonWithArrayInIt.getJSONArray("items"); 

    Map<String,String> ctx = new HashMap<String,String>(); 
    ctx.put("foo.bar", "baz"); 
    Mustache.compiler().standardsMode(true).compile("{{foo.bar}}").execute(ctx); 

    System.out.println("itemised: " + items.toString()); 
} catch(JSONException je) { 
    //Error while creating JSON. 
} 

Ho passato una mappa di dati per far funzionare Mustache. Il metodo è simile al seguente:

public static Map<String, Object> toMap(JSONObject object) 
     throws JSONException { 
    Map<String, Object> map = new HashMap(); 
    Iterator keys = object.keys(); 

    while (keys.hasNext()) { 
     String key = (String) keys.next(); 
     map.put(key, fromJson(object.get(key))); 
    } 

    return map; 
} 

sto seguendo un Mustache Guide per ottenere l'autoformation Baffi. Ma non so come ottenere il risultato che mi aspetto. L'uscita dovrebbe essere la seguente:

<h1>Colors</h1> 
<li><strong></strong></li> 
<li><a href="#Green">green</a></li> 
<li><a href="#Blue">blue</a></li> 

risposta

1

Penso che avete bisogno di ripensare un po 'il modello Baffi. La biblioteca jMustache (che presumo che si sta utilizzando) sembra trattare sempre {{# entità come liste e iterare il loro contenuto, a prescindere dal tipo di dati passati in

Qualcosa del genere dovrebbe funzionare:.

Questo produrrà un'ancora HMTL solo se viene fornito un valore "link", evitando così il problema della condizione jMustache. Così il modello JSON sarebbe simile a questa:

{ 
"header": "Colors", 
"items": [ 
     {"caption": "title"}, 
     {"caption": "red", "url": "#Red"}, 
     {"caption": "green", "url": "#Green"}, 
     {"caption": "blue", "url": "#Blue"} 
    ] 
} 

Infine, è necessario convertire il JSON a qualcosa jMustache capisce. Non ho mai visto o sentito parlare della classe "HTTPFunctions" in nessuna libreria che ho usato, ma ho fatto qualche mappatura simile usando Gson in passato. Si noti che questo è un molto semplice implementazione e potrebbe essere necessario estenderlo alle proprie esigenze:

private Map<String, Object> getModelFromJson(JSONObject json) throws JSONException { 
    Map<String,Object> out = new HashMap<String,Object>(); 

    Iterator it = json.keys(); 
    while (it.hasNext()) { 
     String key = (String)it.next(); 

     if (json.get(key) instanceof JSONArray) { 

      // Copy an array 
      JSONArray arrayIn = json.getJSONArray(key); 
      List<Object> arrayOut = new ArrayList<Object>(); 
      for (int i = 0; i < arrayIn.length(); i++) { 
       JSONObject item = (JSONObject)arrayIn.get(i); 
       Map<String, Object> items = getModelFromJson(item); 
       arrayOut.add(items); 
      } 
      out.put(key, arrayOut); 
     } 
     else { 

      // Copy a primitive string 
      out.put(key, json.getString(key)); 
     } 
    } 

    return out; 
} 

Questo test JUnit Basic illustra la teoria: http://www.pasteshare.co.uk/p/841/

0

Basta usare

Map<String, Object> s = HTTPFunctions.toMap(new JSONObject(template)); 
+0

ringrazia :) ma ora come convertire questo in modello di formato html? – yakusha

+0

Sebbene il codice sia apprezzato, dovrebbe sempre avere una spiegazione di accompagnamento. Questo non deve essere lungo ma è previsto. – peterh