如何使用JSON /字符串在Android上执行胡子模板? [英] How to execute Mustache template with JSON/String on 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 Map
s - 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屋!