Spring -roo JSON REST Controllers Manage Date Fields

I have a data object that I use in two ways: I populate the table with some of my data when the page loads, and when you click on the row of this column, I AJAX look at the details of this element and display them in the form fields. I use Spring-Roo generated server-side REST endpoints and Backbone.js on the client.

When the table loads, the date fields have the format that I expect based on my MySQL database ("yyyy-MM-dd"). When I get AJAX data, the date fields come to me as Unix time values ​​(for example, "1323666000000").

I can convert it on the client side, but it's stupid. Any idea how I can get my json controller not to do this?

I tried pushing these fields into my .java file and messing around with @DateTimeFormat annotation, but I don't see that this has any meaning.

+4
source share
1 answer

You can convert the date to any format that is required for your JSON response.

In your case, you always used the default JSON date converter for fields like java.util.Date . This is basically what is generated for you using Spring Roo. Take a look at your aspects of * _Roo_Json and you will find smth. eg:

 public java.lang.String PizzaOrder.toJson() { return new JSONSerializer().exclude("*.class").serialize(this); } 

Such an implementation uses the flexjson.transformer.BasicDateTransformer class to convert the date for you. It runs as follows:

 public class BasicDateTransformer extends AbstractTransformer { public void transform(Object object) { getContext().write(String.valueOf(((Date) object).getTime())); } } 

You want to use another, more powerful transformer. Fortunately, it comes with your Roo and is called flexjson.transformer.DateTransformer . Now, to format dates correctly, simply replace the default new transformer, for example. eg:

 public java.lang.String PizzaOrder.toJson() { return new JSONSerializer().exclude("*.class") .transform(new DateTransformer("MM/dd/yyyy"), Date.class) .serialize(this); } 

What all: -)

Know that you can also apply different Date transformations (and not only) to different fields, such as:

 transform(new DateTransformer("MM/dd/yyyy"), "person.birthday") 

For more information on flexjson, see the FLEXJSON project page .

+4
source

Source: https://habr.com/ru/post/1383649/


All Articles