spring boot @ResponseBody 转换 JSON 时 Date 类型处理方法 , 这里一共有两种不同解析方式 (Jackson 和 FastJson 两种方式, springboot 我用的 1.x 的版本)
第一种方式: 默认的 json 处理是 jackson 也就是对 configureMessageConverters 没做配置时
mybatis 数据查询返回的时间, 是一串数字, 如何转化成时间. 两种方法, 推荐第一种
方法一:
可以在 apllication.property 加入下面配置就可以
- #时间戳统一转换
- spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
- spring.jackson.time-zone=GMT+8
方法二:
- @JsonFormat(timezone = "GMT+8", pattern = "yyyyMMddHHmmss")
- private Date createTime;
第二种方式: 当 configureMessageConverters 配置为 FasJson 处理时;
方法一: 全局配置: fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
- @Configuration
- public class webMvcConfig extends WebMvcConfigurerAdapter {
- @Override
- public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
- super.configureMessageConverters(converters);
- FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
- FastJsonConfig fastJsonConfig = new FastJsonConfig();
- fastJsonConfig.setSerializerFeatures(
- SerializerFeature.WriteNullListAsEmpty,
- SerializerFeature.WriteMapNullValue,
- SerializerFeature.WriteNullStringAsEmpty
- );
- // 此处是全局处理方式
- fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
- fastConverter.setFastJsonConfig(fastJsonConfig);
- List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
- supportedMediaTypes.add(MediaType.ALL); // 全部格式
- fastConverter.setSupportedMediaTypes(supportedMediaTypes);
- converters.add(fastConverter);
- }
- }
方法二: 在所需要的字段上配置 (比较灵活的方式, 根据不同需求转换):
- @JSONField(format="yyyyMMdd")
- private Date createTime;
说明: 这里如果字段和全局都配置了 , 最后是以全局转换
来源: https://www.cnblogs.com/liran123/p/9516573.html