springboot后端使用LocalDate接收日期的問題解決
報錯內(nèi)容
Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDate' for property 'xxxx';
nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.time.LocalDate] for value '2021-10-03';
nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2021-10-03]
當后端的實體類 使用jdk8的時間時,會報以上的問題
這個時候就需要使用 @DateTimeFormat(pattern = “yyyy-MM-dd”) 注解
該注解中的pattern 要和前端傳過來的日期格式保持一致
如果是 LocalDateTime 可以使用 @DateTimeFormat(pattern = “yyyy-MM-dd HH:mm:ss”)
這是反序列化時的做法,當序列化時 也就是后端傳給前端時,轉(zhuǎn)換時間格式使用 @JsonFormat(pattern = “yyyy-MM-dd”, timezone = “GMT+8”) 注解
@DateTimeFormat(pattern = "yyyy-MM-dd") @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") private LocalDate beginTime;
也可以設置全局
@Bean @Primary @ConditionalOnMissingBean(ObjectMapper.class) public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) { ObjectMapper objectMapper = builder.createXmlMapper(false).build(); // 全局配置序列化返回 JSON 處理 SimpleModule simpleModule = new SimpleModule(); //封裝類型 Long ==> String simpleModule.addSerializer(Long.class, ToStringSerializer.instance); simpleModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN))); simpleModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN))); simpleModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN))); simpleModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN))); simpleModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN))); simpleModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN))); objectMapper.registerModule(simpleModule); objectMapper.setDateFormat(new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN)); objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8")); return objectMapper; }
到此這篇關于springboot后端使用LocalDate接收日期的問題解決的文章就介紹到這了,更多相關springboot LocalDate接收日期內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決Spring配置文件中bean的property屬性中的name出錯問題
這篇文章主要介紹了解決Spring配置文件中bean的property屬性中的name出錯問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07Mybatis動態(tài)SQL?foreach批量操作方法
這篇文章主要介紹了Mybatis動態(tài)SQL?foreach批量操作方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-03-03解析ConcurrentHashMap: 預熱(內(nèi)部一些小方法分析)
ConcurrentHashMap是由Segment數(shù)組結(jié)構(gòu)和HashEntry數(shù)組結(jié)構(gòu)組成。Segment的結(jié)構(gòu)和HashMap類似,是一種數(shù)組和鏈表結(jié)構(gòu),今天給大家普及java面試常見問題---ConcurrentHashMap知識,一起看看吧2021-06-06