Search code examples
javathymeleaf

How to serialize object correctly in Thymeleaf?


I have nested complex object in my controller:

class ClientDTO {
public InnerClass cl;

public getCl()...
public setCl()...
}

InnerClass contains some primitive data types Integer,String.

My controller just returns this ClientDTO. On my thymeleaf template I've got :

var client=[[${client}]]

Here client is a ClientDTO value, returned from the controller. This variable client is serialized into ru.foo.ClientDTO@6543785 which is incorrect.

How can I fix it to receive correct client object in form of json like this: ClientDTO{cl: {....}} ?


Solution

  • It's hard to say where exactly you want this based on your description, but I am assuming your var definition is in a script tag. If so, use

    <script data-th-inline="javascript">

    to make thymeleaf properly create the variable. Secondly, wrap client like this:

    var client = /*[[${client}]]*/ {};

    to ensure there is a default and preserve natural templating, with the default being {} or '' or such. From there you can convert to json if you wish.