我正在尝试使用 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 View 和 java 模型“Blog”的例子。 ,但是如果不为该 json 使用 java 模型对象就不能实现吗?
最佳答案
刚刚发现将 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));
}
}
关于java - 如何在 Handlebars.java 中使用 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24657032/