Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

java - json date format in spring-boot

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are three things that you need to do to format the date as yyyy-MM-dd:

  1. Add a dependency on 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.
  2. Configure Jackson not to format dates as timestamps by adding spring.jackson.serialization.write-dates-as-timestamps: false to your application.properties file.
  3. Annotate the 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...