如果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); } }