springboot后端使用LocalDate接收日期的问题解决
报错内容
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”)
这是反序列化时的做法,当序列化时 也就是后端传给前端时,转换时间格式使用 @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接收日期内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Spring的@Validation和javax包下的@Valid区别以及自定义校验注解
这篇文章主要介绍了Spring的@Validation和javax包下的@Valid区别以及自定义校验注解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2021-01-01
Feign调用服务时丢失Cookie和Header信息的解决方案
这篇文章主要介绍了Feign调用服务时丢失Cookie和Header信息的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-03-03
springsecurity中http.permitall与web.ignoring的区别说明
这篇文章主要介绍了springsecurity中http.permitall与web.ignoring的区别说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-08-08


最新评论