spring boot项目中LocalDateTime的json序列化处理

1. 默认的Jackson配置

spring boot默认是采用Jackson来做json的序列化的。当我们使用LocalDateTime来表示时间的时候,如果不做相应的配置,那么前端接收到的时间就会是一个数组,类似于这种:
"createTime": [2099, 12, 31, 23, 59, 59]
引发这个问题的原因是json序列化的时候没有配置规则,所以采用了默认的序列化规则,返回了数组。所以解决的方法就是配置一个规则:

@Configuration
public class WebConfig {
     @Bean
     public Jackson2ObjectMapperBuilderCustomizer customizeLocalDateTimeFormat() {
         return jacksonObjectMapperBuilder -> {
             DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
             LocalDateTimeDeserializer deserializer = new LocalDateTimeDeserializer(formatter);
             LocalDateTimeSerializer serializer = new LocalDateTimeSerializer(formatter);
             jacksonObjectMapperBuilder.serializerByType(LocalDateTime.class, serializer);
             jacksonObjectMapperBuilder.deserializerByType(LocalDateTime.class, deserializer);
         };
     }
}

这样,所有的时间格式都会按照"yyyy-MM-dd HH:mm:ss"来显示,如果需要特殊的格式,例如"yyyy年MM月dd日",那么只需要在字段上加上@JsonFormat(pattern = "yyyy年MM月dd日")注解即可。
例如:

        @JsonFormat(pattern = "yyyy年MM月dd日")
        @ApiModelProperty(value = "申请日期 yyyy年MM月dd日")
        private LocalDateTime applyDate;

2.使用了Fastjson

如果我们在项目中引入了其他的json处理依赖,那么就会覆盖掉Jackson而使用引入的依赖作为json序列化的工具。这里以Fastjson举例,方法和1中是一样的,只不过实现有点差别。

@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.PrettyFormat,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.DisableCircularReferenceDetect
        );
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        converters.add(0, fastJsonHttpMessageConverter);
    }
}

特殊的格式:

        @JSONField(format= "yyyy年MM月dd日")
        @ApiModelProperty(value = "申请日期 yyyy年MM月dd日")
        private LocalDateTime applyDate;
  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值