如果SpringBoot没有配置maven的json依赖,默认使用JacksonJson,那么你可以像网上资料介绍的那样进行配置,如下:

@Configuration
public class WebMvcConfig {

    @Bean
    public Converter<String, LocalDate> localDateConverter() {
        return new Converter<String, LocalDate>() {
            @Override
            public LocalDate convert(String source) {
                return DateUtil.parseDate(source);
            }
        };
    }

    @Bean
    public Converter<String, LocalDateTime> localDateTimeConverter() {
        return new Converter<String, LocalDateTime>() {
            @Override
            public LocalDateTime convert(String source) {
                return DateUtil.parseDateTime(source);
            }
        };
    }
}

如果你在maven中有配置FastJson,Spring的加载机制会优先使用手动配置的FastJson而不是JacksonJson。

但是由于FastJson对SpringMVC的兼容不好,上面的方式并不能让自定义格式全局有生效,经过debug代码发现,需要使用下面的方式配置,才能全局生效:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @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);
    }
}

 

相关文章:

  • 2021-06-08
  • 2022-12-23
  • 2021-08-11
  • 2021-09-16
  • 2022-12-23
  • 2020-07-21
  • 2023-01-08
  • 2022-01-20
猜你喜欢
  • 2022-01-05
  • 2021-09-16
  • 2021-10-08
  • 2021-08-01
  • 2021-10-22
  • 2021-12-24
  • 2022-12-23
相关资源
相似解决方案