如何在Handlebars.java中使用json

gop*_*anj 1 java handlebars.js

我正在尝试使用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));
    }
}
Run Code Online (Sandbox Code Playgroud)

我期待输出为

你好,世界!

而我正好

你好 !

我错过了什么?我在https://github.com/jknack/handlebars.java上看过像Jackson模型"博客"的杰克逊观点的例子,但如果不使用json的java模型对象,这不可能实现吗?

gop*_*anj 5

刚发现传递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));
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 最终,这是我的问题与handlebars.java ...为它的所有铃声和口哨他们_failed_提供一个简单的例子,将JSON字符串或Java Map对象作为模板的输入...但如果我没有找到把手.java如此令人沮丧我不会发现有一个单独的项目也是mustache.js的衍生物恰当地命名为[mustache.java](https://github.com/spullara/mustache.java) (5认同)