【问题标题】:How to execute Mustache template with JSON/String on Android?如何在 Android 上使用 JSON/String 执行 Mustache 模板?
【发布时间】:2012-09-07 09:16:51
【问题描述】:


我有 String 带有模板库的对象,例如:

<h1>{{header}}</h1>
{{#bug}}
{{/bug}}

{{#items}}
  {{#first}}
    <li><strong>{{name}}</strong></li>
  {{/first}}
  {{#link}}
    <li><a href="{{url}}">{{name}}</a></li>
  {{/link}}
{{/items}}

{{#empty}}
  <p>The list is empty.</p>
{{/empty}}

我想提取另一个代表JSONObjectString 对象并将其字段放入模板中:

{
  "header": "Colors",
  "items": [
      {"name": "red", "first": true, "url": "#Red"},
      {"name": "green", "link": true, "url": "#Green"},
      {"name": "blue", "link": true, "url": "#Blue"}
  ],
  "empty": false
}

最后我会得到代表 HTML 结构的String

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

我不想使用任何 POJO 或 Maps - 仅使用标准 String 对象,或者将第二个 String 转换为 JSONObject 以将其用作模板的上下文。
有人能给我举个例子吗?
谢谢。

编辑:我在执行模板时对模板/JSON 结构一无所知 - 我必须使用未知模板/JSON 并假设它们是正确的。

【问题讨论】:

    标签: java android json string mustache


    【解决方案1】:

    我找不到处理纯 String 对象的方法 - 我正在将 JSONObject 转换为 Map 以使其与 Mustache 一起使用。这是转换代码:

    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;
    }
    
    public static List toList(JSONArray array) throws JSONException
    {
        List list = new ArrayList();
        for (int i = 0; i < array.length(); i++)
        {
            list.add(fromJson(array.get(i)));
        }
        return list;
    }
    
    private static Object fromJson(Object json) throws JSONException
    {
        if (json instanceof JSONObject)
        {
            return toMap((JSONObject) json);
        } else if (json instanceof JSONArray)
        {
            return toList((JSONArray) json);
        } else
        {
            return json;
        }
    }
    

    用法:

    mustacheTemplate.execute(JSONUtils.toMap(new JSONObject(myString)));
    

    【讨论】:

    • 最后一个问题,如何从模板和 json 数据中获取 html?
    • 我不确定你的问题是否正确,但“执行”方法返回格式化的 HTML 字符串,您可以在 WebView 中使用它。
    • 我想获取格式化的 html 字符串,但我不明白 mustacheTemplate.execute() 来自哪里。你能在聊天中给我解释一下吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    • 1970-01-01
    相关资源
    最近更新 更多