In my project setup, I've created sample API's and returns current date. But it returns milliseconds. What is the problem in serialise java object to json.? Here I've attached screen shots for your reference.
code:`@GetMapping("/refresh/core/cache/demo")
public Date getDate(){
log.info("Current date is : {}",new Date());
return new Date();
}
In my attachments, log prints correct date format but it returns in millisecond. why it did not return date as a date format.?
CodePudding user response:
Json supports only few data types. Those are Number, String, Boolean,
Array, Object and null. We need to send the in these formats only.
We need to format the date and return the String as response.
We need to Convert the date from Date to String.
@GetMapping("/refresh/core/cache/demo")
public String getDate(){
log.info("Current date is : {}",new Date());
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
retutn formatter.format(date);
}
CodePudding user response:
There are different solutions.
Add a dependency on
com.fasterxml.jackson.datatype:jackson-datatype-joda
.I think you may already have this dependency. Configure Jackson not to format dates as timestamps by addingspring.jackson.serialization.write-dates-as-timestamps: false
to your application.properties file.Annotate the Date field or getter method with
@JsonFormat(pattern="yyyy-MM-dd")