Converting a Java object to a Javascript object using velocity

If a have a Java object (lets say a User object), and I use velocity to template the page so I can access a field in the user object like ${user.id}, is there an easy way to convert this into a javascript object (so I can access the fields of the User object)?

I can assign a value to javascript variable like

var id = "${user.id}";

but if i do

var user = "${user}";

this isn't true:

 id == user.id;

And I would rather not have to do

  var user = { id: "${user.id}" ...}

Answers


Maybe you should transform your user object to a JSON.

You can create a utility method that uses reflection and gets each attribute from an object and put in a String. Maybe you can create an annotation to mark which attributes should be included in the JSON.

This way you send to your template something like this

"{id: '1', name:'stevebot'}"

And in you velocity file

var user = ${user};

Need Your Help

inserting data from multiple tables into one separate table

php mysql sql

First of all, I know MySQL is a depreciated language, but my supervisor insists I use it.