问题
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.
回答1:
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.Date
type 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:
public java.lang.String PizzaOrder.toJson() {
return new JSONSerializer().exclude("*.class").serialize(this);
}
Such an implementation uses the flexjson.transformer.BasicDateTransformer
class to transform the date for you. It is implemented like this:
public class BasicDateTransformer extends AbstractTransformer {
public void transform(Object object) {
getContext().write(String.valueOf(((Date) object).getTime()));
}
}
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:
public java.lang.String PizzaOrder.toJson() {
return new JSONSerializer().exclude("*.class")
.transform(new DateTransformer("MM/dd/yyyy"), Date.class)
.serialize(this);
}
That's all :-)
Know that you may also apply different Date
(and not only) transformations for different fields like this:
transform(new DateTransformer("MM/dd/yyyy"), "person.birthday")
For more info about the flexjson take a look at FLEXJSON project page.
来源:https://stackoverflow.com/questions/8311962/spring-roo-rest-json-controllers-mangle-date-fields