我正在尝试使用handlebars.java来应用json数据。我从https://github.com/jknack/handlebars.java中取了下面的例子,它适用于handlebars.js,我希望同样的方法也适用于handlebars.java
public class TestHandlebars {
public static void main(String[] args) throws Exception {
String json = "{\"name\": \"world\"}";
Handlebars handlebars = new Handlebars();
handlebars.registerHelper("json", Jackson2Helper.INSTANCE);
Context context = Context
.newBuilder(json)
.resolver(JsonNodeValueResolver.INSTANCE,
JavaBeanValueResolver.INSTANCE,
FieldValueResolver.INSTANCE,
MapValueResolver.INSTANCE,
MethodValueResolver.INSTANCE
)
.build();
Template template = handlebars.compileInline("Hello {{name}}!");
System.out.println(template.apply(context));
}
}我期望输出结果为
你好,世界!
而我得到的只是
您好!
我遗漏了什么?我在https://github.com/jknack/handlebars.java上见过像Jackson views和java模型"Blog“这样的例子,但是不使用java模型对象就不能实现吗?
发布于 2014-07-10 03:20:41
我刚刚发现将json作为JsonNode对象传递是可行的。
public class TestHandlebars {
public static void main(String[] args) throws Exception {
String json = "{\"name\": \"world\"}";
JsonNode jsonNode = new ObjectMapper().readValue(json, JsonNode.class);
Handlebars handlebars = new Handlebars();
handlebars.registerHelper("json", Jackson2Helper.INSTANCE);
Context context = Context
.newBuilder(jsonNode)
.resolver(JsonNodeValueResolver.INSTANCE,
JavaBeanValueResolver.INSTANCE,
FieldValueResolver.INSTANCE,
MapValueResolver.INSTANCE,
MethodValueResolver.INSTANCE
)
.build();
Template template = handlebars.compileInline("Hello {{name}}!");
System.out.println(template.apply(context));
}
}发布于 2017-02-24 08:00:37
使用Gson,你可以很容易地做到这一点,而不需要注册一堆转换器。
String data = "{\"subject\": \"World\"}";
String decoration = "Hello {{subject}}!";
Handlebars handlebars = new Handlebars();
Gson gson = new Gson();
Type type = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, Object> map = gson.fromJson(data, type);
Template template = handlebars.compileInline(decoration);
Context context = Context.newBuilder(map).build();
String output = template.apply(context);https://stackoverflow.com/questions/24657032
复制相似问题