springboot DTO字符字段与日期字段的转换问题
不会自动转换string与date
主要是这个意思,前端提交的JSON里,日期是一个字符串,而对应后端的实体里,它是一个Date的日期,这两个在默认情况下是不能自动转换的,我们先看一下实体实体
public class UserDTO { private String name; private String email; private Boolean sex; private Double total; private BigDecimal totalMoney; private Date birthday;}
客户端提交的json对象
{ 'email': null, 'name': 'lr', 'total':3, 'totalMoney':1, 'birthday':'1983-03-18'}
服务端收到的实体DTO是正常的
而在服务端响应的结果却不是日期,而是一个时间戳
{ 'name': 'lr', 'email': null, 'sex': null, 'total': '3.00', 'totalMoney': 0.0000, 'birthday': 416793600000}
我们看到日期型的birthday在响应到前端还是一个时间戳,如果我们希望响应到前端是一个日期,那需要为这个DTO实体添加JsonFormat注解
public class UserDTO { private String name; private String email; private Boolean sex; private Double total; private BigDecimal totalMoney; @JsonFormat(pattern = 'yyyy-MM-dd', timezone = 'GMT+8') private Date birthday;}
也可以通过配置文件进行设置
spring: jackson.date-format: yyyy-MM-dd jackson.time-zone: GMT+8 jackson.serialization.write-dates-as-timestamps: false
这样,在服务端向前端响应结果就变成了
使用configureMessageConverters方法全局处理
springboot2.x可以实现WebMvcConfigurer 接口,然后重写configureMessageConverters来达到定制化日期序列化的格式:
Configuration@EnableWebMvc //覆盖默认的配置public class WebMvcConfigurerImpl implements WebMvcConfigurer { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter(); ObjectMapper objectMapper = new ObjectMapper(); // 时间格式化 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.setDateFormat(new SimpleDateFormat('yyyy-MM-dd'));//只能是一个日期格式化,多个会复盖 }}
如上图所示,如果希望为getup字段添加时分秒,需要在DTO上使用@JsonFormat(pattern='yyyy-MM-dd HH:mm:ss')注解即可。
总结
到此这篇关于springboot~DTO字符字段与日期字段的转换问题的文章就介绍到这了,更多相关springboot字符字段与日期字段转换内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!
相关文章:
