I am returning a JSON as a response from the controller. I want to format the date fields in this response.
Controller-
@RequestMapping(value = "/call", method = RequestMethod.GET)
public SampleDTO get()
{
......
return sampleDTO;
}
SampleDTO-
{
"date" : "2020-03-10T08:57:58+0000",
"text" : "abc"
}
I want to format the date field to dd-MM-yyyy
To do this I add the @JsonFormat annotation to the bean class of SampleDTO.
SampleDTO.java -
import java.util.Date;
public class SampleDTO
{
@JsonFormat(pattern = "dd-MM-yyyy")
private Date date;
private String text;
@JsonFormat(pattern = "dd-MM-yyyy")
public void setDate(final Date date)
{
this.date = date;
}
@JsonFormat(pattern = "dd-MM-yyyy")
public Date getDate()
{
return date;
}
public void setText(final String text)
{
this.text = text;
}
public String getText()
{
return text;
}
}
Still, I am getting this format in the response on my browser.
"date" : "2020-03-10T08:57:58+0000"
EDIT 1:
Instead of returning the sampleDTO, converting it to String directly in the code works perfectly fine.
This works like a charm:
SampleDTO sampleDTO = new SampleDTO();
sampleDTO.setCreated(new Date());
ObjectMapper om = new ObjectMapper();
return om.writeValueAsString(sampleDTO);
Date. That class is poorly designed and long outdated. UseLocalDatefrom java.time, the modern Java date and time API. (2) In your JSON use ISO 8601 format, soyyyy-MM-dd, notdd-MM-yyyy.Dateclass all over the place in the latest version of Hybris. In my JSON I have a specific requirement to show the date in this format, so I can't change it.