1、問題背景
最近項目在通過sql查詢數(shù)據(jù)的時候,報了如下錯誤:
Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Java 8 date/time type `java.time.LocalDateTime` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling (through reference chain: com.ytx.dependency.common.utils.Result["data"]->com.ytx.ccserverform.modules.data.dto.ViewModelDataVO["list"]->java.util.ArrayList[0]->java.util.HashMap["occurrence_time"])
2、分析過程
異常信息:Java 8 date/time type `java.time.LocalDateTime` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310"?
從異常信息中我們解讀到 java8 Jackson庫在默認情況下不支持LocalDateTime序列化和反序列化。
于是看了數(shù)據(jù)表的字段,確實有datetime日期類型的字段, java8將?java.time.LocalDateTime
?序列化為 JSON 時,就會報以上錯誤。
3、解決方法
1、配置全局配置(親測有效)
在Springboot?WebMvcConfigurer其全局配置中增加以下配置,代碼如下:
@Configuration
public class WebJsonConverterConfig implements WebMvcConfigurer {
/**
* 解決Java8 日期序列化問題
* jackson默認不支持java8 LocalDateTime的序列化和反序列化
*
* @param converters
*/
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.registerModule(new JavaTimeModule());
messageConverter.setObjectMapper(objectMapper);
converters.add(0, messageConverter);
}
}
2、用阿里的FastJson替換ObjectMapper
4、總結(jié)
對于這個問題解決得方案有很對,核心還是對LocalDate進行進行序列器解析,將LocalDateTime轉(zhuǎn)為Date。大家根據(jù)自己得需要選擇合適得方案,本文就不一一列舉所有方案了。文章來源:http://www.zghlxwxcb.cn/news/detail-857866.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-857866.html
到了這里,關(guān)于解決SpringBoot日期序列化問題:[Java 8 date/time type `java.time.LocalDateTime` not supported by default]的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!