在thymeleaf模板中对象到JSON序列化

时间:2016-11-29 19:16:00

标签: spring-mvc thymeleaf

在百里香叶中是否有一种方法可以从上下文输出对象的json。我可以在控制器内完成,但并不是真的想要。

控制器:

@RequestMapping("/{projectId}/edit")
public String editProject(Model model, @PathVariable Long projectId) {
    Project project = projectRepo.findOne(projectId);
    // Below line works, but I want to put the object to the model
    // model.addAttribute("project", new ObjectMapper().writeValueAsString(project));
    model.addAttribute("project", project);
    return "project/edit";
}

部分模板:

<script>
    var app = new Vue({
        el: '#app',
        data: {
            project: [(${project})]
        }
    });
</script>

1 个答案:

答案 0 :(得分:10)

Thymeleaf开箱即用,我认为您只需要添加th:inline="javascript"

http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#script-inlining-javascript-and-dart

<script th:inline="javascript">
    var app = new Vue({
        el: '#app',
        data: {
            project: /*[[${project}]]*/ {}
        }
    });
</script>