如何使用JSON /字符串在Android上执行胡子模板? [英] How to execute Mustache template with JSON/String on Android?

查看:173
本文介绍了如何使用JSON /字符串在Android上执行胡子模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

结果
我有字符串与模板的基本对象,是这样的:


I have String object with template base, something like:

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

我要拉另一个字符串对象重新presenting 的JSONObject 键,把它的领域为模板:

I want to pull another String object representing JSONObject and put its fields into template:

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

在最后,我会得到字符串重新presenting HTML结构:

In the end I would get String representing HTML structure:

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

我不希望使用任何的POJO或地图秒 - 只使用标准的字符串对象或交替转换第二个字符串的JSONObject 来使用它作为一个模板的上下文。结果
可能有人给我任何例子,如何实现呢?结果
谢谢。

I don't want to use any POJOs or Maps - only use standard String objects or alternatively convert second String into JSONObject to use it as a template's context.
Could someone give me any example how to achieve that?
Thanks.

修改:我不知道模板/ JSON 任何结构在执行模板 - 我有未知的模板,播放/ JSON ,并认为他们是正确的。

Edit: I don't know anything about template/JSON structure while executing template - I have to play with unknown template/JSON and assume that they are correct.

推荐答案

我找不到办法​​纯字符串对象的工作 - 我转换的JSONObject 地图来得到它与小胡子的工作。这是code转换:

I couldn't find way to work on pure String objects - I am converting JSONObject to Map to get it working with Mustache. This is code for conversion:

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 /字符串在Android上执行胡子模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆