使用spring boot在json输出中的日期格式 [英] Date format in the json output using spring boot

查看:253
本文介绍了使用spring boot在json输出中的日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用spring boot来创建REST应用程序。我有一个DTO,如下所示:

I am working on spring boot for creating a REST application. And I have a DTO as shown below:

public class Subject {

private String uid;
private String number;
private String initials;
private Date dateOfBirth;

我使用Spring-Hateos并且我的控制器的重新类型是 ResponseEntity< ;资源与LT;资源与LT受试者GT;>> 。我需要以yyyy-mm-dd格式显示日期。

And I use Spring-Hateos and the reurn type of my controller is ResponseEntity<Resources<Resource<Subject>>>. I need the date to be displayed in the "yyyy-mm-dd" format.

推荐答案

如果你让杰克逊与你合作应用程序将您的bean序列化为JSON格式,然后您可以使用Jackson anotation @ JsonFormat 将您的日期格式化为指定格式。

如果您需要将日期转换为 yyyy-MM-dd 格式,您需要在要应用此格式的字段上方指定 @JsonFormat

If you have Jackson integeration with your application to serialize your bean to JSON format, then you can use Jackson anotation @JsonFormat to format your date to specified format.
In your case if you need your date into yyyy-MM-dd format you need to specify @JsonFormat above your field on which you want to apply this format.

例如:

public class Subject {

     private String uid;
     private String number;
     private String initials;

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

     //Other Code  

}  

来自Docs:


注释,用于配置如何序列化属性
的值的详细信息。

annotation used for configuring details of how values of properties are to be serialized.

更多参考文档

希望这有帮助。

这篇关于使用spring boot在json输出中的日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆