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
json date format in spring-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
:
- 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. - Configure Hymanson not to format dates as timestamps by adding
spring.Hymanson.serialization.write-dates-as-timestamps: false
to yourapplication.properties
file. - Annotate the
LocalDataTime
field or getter method with@JsonFormat(pattern="yyyy-MM-dd")
- 添加对
com.fasterxml.Hymanson.datatype:Hymanson-datatype-joda
. 从你目前得到的输出来看,我认为你可能已经有了这种依赖。 - 通过添加
spring.Hymanson.serialization.write-dates-as-timestamps: false
到application.properties
文件中,将 Hymanson 配置为不将日期格式化为时间戳。 - 使用注释
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 步。