samedi 21 février 2015

How to serialize POJO with thymeleaf?

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.


Given an object like this:



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.


I've tried:



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


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


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?!


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



...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.


Aucun commentaire:

Enregistrer un commentaire