I am using spring-boot and I have an entity class defined something like this
import org.joda.time.LocalDateTime;
@Entity
public class Project {
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
private LocalDateTime start_date;
...
...
}
When this class is converted to JSON, the field gets converted to the following string representation
{"start_date":[2014,11,15,0,0,0,0],...., ...}
I want to have the json response as yyyy-MM-dd
.
I tried the @DateTimeFormat(iso = ISO.DATE)
annotation and that did not help either.
Is there an easy way to do this conversion to proper json format ?
To take care send date from client as string object, in format yyyy/MM/dd. In Spring Boot application, to add annotation on the date field with the same format.
JSON does not have a built-in type for date/time values. The general consensus is to store the date/time value as a string in ISO 8601 format.
You can get the value of the date field as String by calling the getText() method of JsonParser class and then you can simply convert it into a Date object by using the parse() method of SimpleDateFormat, as you normally parse Date in Java.
Date format conversion yyyy-mm-dd to mm-dd-yyyy.
There are three things that you need to do to format the date as yyyy-MM-dd
:
com.fasterxml.jackson.datatype:jackson-datatype-joda
. Judging by the output you're getting at the moment, I think you may already have this dependency.spring.jackson.serialization.write-dates-as-timestamps: false
to your application.properties
file.LocalDataTime
field or getter method with @JsonFormat(pattern="yyyy-MM-dd")
Note: You'll need to use Spring Boot 1.2 for step 2 to work.
Without additional dependency - the only thing I had to do is:
To take care send date from client as string object, in format yyyy/MM/dd
In Spring Boot application, to add annotation on the date field with the same format
public class Foo
{
@JsonFormat(pattern = "yyyy/MM/dd")
private Date dueDate;
}
Using Spring Boot 2.3.5 version
Another option, instead of step 2, to modify application.properties file, add there the format for any Date object:
spring.jackson.date-format=yyyy/MM/dd
You can use @JsonFormat annotation in and the desired pattern like this without using any dependency :
@JsonFormat(pattern="yyyy-MM-dd")
private Date created_At;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With