Hi
I try to format a json output with the @DateTimeFormat annotation.
Here my simple test controller:
And the User objectCode:@Controller public class TestController { @RequestMapping("/doSomething") @ResponseBody public User doSomething() { User aUser = new User(); aUser.setName("aName"); Calendar cal = new GregorianCalendar(1980, Calendar.MARCH, 22); aUser.setBirthDay(cal.getTime()); return aUser; } }
Unfortunately this does not work. The output shows the date in millisecondsCode:public class User { private String name; @DateTimeFormat(iso=ISO.DATE) private Date birthDay; public String getName() {return name; } public void setName(String name) { this.name = name; } public Date getBirthDay() { return birthDay; } public void setBirthDay(Date birthDay) { this.birthDay = birthDay; } }
{"name":"aName","birthDay":322527600000}
I also tried to annotate the get method but with the same result.
So I'm wondering if this use of @DateTimeFormat is supported. Or is there something I am doing wrong.
It's not really a big problem because I can use the Jackson annotation @JsonSerialize.
Code:@JsonSerialize(using=MyDateSerializer.class) public Date getBirthDay() { return birthDay; }This way the output isCode:public class MyDateSerializer extends JsonSerializer<Date> { @Override public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz"); jgen.writeString(formatter.format(value)); } }
{"name":"aName","birthDay":"1980-03-22T00:00:00CET"}
Regards
Ralph


Reply With Quote
