如何用百里香来序列化POJO? [英] How to serialize POJO with thymeleaf?

查看:79
本文介绍了如何用百里香来序列化POJO?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用百里香在<script>标记中将POJO(普通的Java对象)作为普通的Json插入.我还将Spring MVC用作框架.

I would like to insert a POJO (plain old java object) as normal Json within a <script> tag using thymeleaf. I'm also using Spring MVC as framework.

给出这样的对象:

class Data {
   String a;
   int b;
   Object c;
}

我想获得像这样的东西作为渲染模板:

I'd like to obtain something like this as rendered template:

<script>
   var data = {
      a: "foo",
      b: 123,
      c: {...}
    }
</script>

直到我还没有找到使用百里香叶渲染此效果的方法.

Until, I haven't found a way to render this using thymeleaf.

我尝试过:

<script th:inline="javascript">
    var data = /*[[${myDataObj}]]*/ {};
</script>

但这失败了,因为显然百里香无法序列化POJO.

But this failed because apparently thymeleaf is incapable of serializing POJOs.

然后,我还尝试提供已序列化为json的对象:

Then, I've also tried to provide the object already serialized as json:

<script th:inline="javascript">
    var data = /*[[${myDataAsJson}]]*/ {};
</script>

但是这也不起作用,因为它将再次转义该字符串.再次,百里香叶似乎无法提供行未转义的字符串.

but this doesn't work either because it'll escape the string again. Again, there seems no way in thymeleaf to provide row unescaped strings.

...现在糟透了...如何使用百里香叶在脚本标签中插入对象?!

...now this sucks ...how to insert an object in a script tag using thymeleaf?!

显然,这是自2012年以来的一个问题,他们似乎并未给予过多考虑:

Apparently, this is an issue since 2012 that they don't appear to give much consideration:

  • https://github.com/thymeleaf/thymeleaf/issues/12
  • https://github.com/thymeleaf/thymeleaf/issues/81

...我的问题是:对此有任何解决方法吗?要使用百里香序列化POJO?有点烂.如果我不太依赖它,我会把它扔掉,但是现在它代表着很多工作来改变这种依赖关系.

...my question is: is there any workaround for this? To serialize a POJO using thymeleaf? It kind of sucks badly. If I hadn't so much depending on it I'd throw it away but now it'd represent to much work to change that dependency.

推荐答案

从百里香3开始,它已经实现: https://github.com/thymeleaf/thymeleaf/issues/12

as of thymeleaf 3, it has been implemented: https://github.com/thymeleaf/thymeleaf/issues/12

...他们花了3年多一点时间:/

...it just took them a bit more than 3 years :/

好吧,我还没有真正找到一种好的方法,但这是我的胜过一切"的解决方法:

Ok, I've not really found a good way to do it, but here is my "better than nothing" workaround:

<script th:inline="javascript">
    var jsonString = /*[[${myJsonString}]]*/ "{\"a\":\"... ";
    var data = JSON.parse(jsonString)
</script>

这是不理想的,因为它无用地执行了额外的JSON序列化/反序列化……但至少可以正常工作.

It's not ideal since it uselessly performs an additional JSON serialization/deserialization ...but at least it works.

这篇关于如何用百里香来序列化POJO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆