简体   繁体   English

spring-boot中的json日期格式

[英]json date format in spring-boot

I am using spring-boot and I have an entity class defined something like this我正在使用 spring-boot 并且我有一个实体类定义了这样的东西

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当此类转换为 JSON 时,该字段将转换为以下字符串表示形式

{"start_date":[2014,11,15,0,0,0,0],...., ...}

I want to have the json response as yyyy-MM-dd .我想将 json 响应设为yyyy-MM-dd

I tried the @DateTimeFormat(iso = ISO.DATE) annotation and that did not help either.我尝试了@DateTimeFormat(iso = ISO.DATE)注释,但也没有帮助。

Is there an easy way to do this conversion to proper json format ?有没有一种简单的方法可以将这种转换为正确的 json 格式?

There are three things that you need to do to format the date as yyyy-MM-dd :您需要做三件事才能将日期格式化为yyyy-MM-dd

  1. Add a dependency on com.fasterxml.jackson.datatype:jackson-datatype-joda .添加对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.通过将spring.jackson.serialization.write-dates-as-timestamps: falseapplication.properties文件,将 Jackson 配置为不将日期格式化为时间戳。
  3. Annotate the LocalDataTime field or getter method with @JsonFormat(pattern="yyyy-MM-dd")使用@JsonFormat(pattern="yyyy-MM-dd")注释LocalDataTime字段或 getter 方法

Note: You'll need to use Spring Boot 1.2 for step 2 to work.注意:您需要使用 Spring Boot 1.2 才能执行第 2 步。

Without additional dependency - the only thing I had to do is:没有额外的依赖——我唯一要做的就是:

  1. To take care send date from client as string object , in format yyyy/MM/dd要注意从客户端发送日期作为字符串对象,格式为yyyy/MM/dd

  2. In Spring Boot application, to add annotation on the date field with the same format在 Spring Boot 应用程序中,在日期字段上添加相同格式的注释


public class Foo
{
     @JsonFormat(pattern = "yyyy/MM/dd")
     private Date dueDate;
}

Using Spring Boot 2.3.5 version使用 Spring Boot 2.3.5 版本


Update更新

Another option, instead of step 2, to modify application.properties file, add there the format for any Date object:另一种选择,而不是第 2 步,修改 application.properties 文件,在那里添加任何 Date 对象的格式:

spring.jackson.date-format= yyyy/MM/dd spring.jackson.date-format= yyyy/MM/dd

You can use @JsonFormat annotation in and the desired pattern like this without using any dependency :您可以在不使用任何依赖项的情况下使用 @JsonFormat 注释和所需的模式:

@JsonFormat(pattern="yyyy-MM-dd")
private Date created_At;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM