java spring-boot中的json日期格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27516499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:55:46  来源:igfitidea点击:

json date format in spring-boot

javaspring-boot

提问by Parag Sanghavi

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 格式?

回答by Andy Wilkinson

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.Hymanson.datatype:Hymanson-datatype-joda. Judging by the output you're getting at the moment, I think you may already have this dependency.
  2. Configure Hymanson not to format dates as timestamps by adding spring.Hymanson.serialization.write-dates-as-timestamps: falseto your application.propertiesfile.
  3. Annotate the LocalDataTimefield or getter method with @JsonFormat(pattern="yyyy-MM-dd")
  1. 添加对com.fasterxml.Hymanson.datatype:Hymanson-datatype-joda. 从你目前得到的输出来看,我认为你可能已经有了这种依赖。
  2. 通过添加spring.Hymanson.serialization.write-dates-as-timestamps: falseapplication.properties文件中,将 Hymanson 配置为不将日期格式化为时间戳。
  3. 使用注释LocalDataTime字段或 getter 方法@JsonFormat(pattern="yyyy-MM-dd")

Note:You'll need to use Spring Boot 1.2 for step 2 to work.

注意:您需要使用 Spring Boot 1.2 才能执行第 2 步。