I have a data entity that I use in two ways, I populate a table with some of its data when the page loads, and when you click a row of that column, I AJAX up the details of that item and display them in form fields. I’m using Spring-Roo generated REST endpoints on the server side, and Backbone.js on the client.
When the table loads, date fields have the format I expect, coming straight out of my MySQL database (“yyyy-MM-dd”). When I get my AJAX data, date fields come to me as Unix time values (e.g. “1323666000000”).
I can convert that on the client side, but that’s stupid. Any idea how I can get my json controller to not do this?
I’ve tried pushing those fields into my .java file and messing with the @DateTimeFormat annotation, but I can’t see that makes any difference.
You can transform the date to any format you want for your JSON response.
In your case, you’ve been using the default JSON date transformer all the time for the
java.util.Datetype fields. This is basically what gets generated for you by the Spring Roo. Take a look and in your *_Roo_Json aspects and you will find smth. like this:Such an implementation uses the
flexjson.transformer.BasicDateTransformerclass to transform the date for you. It is implemented like this:What you want is to use a different, more powerfull transformer. Luckily it comes with your Roo and it’s called
flexjson.transformer.DateTransformer. Now, in order to format your dates properly, just replace the default with the new transformer e.g. like this:That’s all 🙂
Know that you may also apply different
Date(and not only) transformations for different fields like this:For more info about the flexjson take a look at FLEXJSON project page.