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接收日期内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
mybatis foreach遍历LIST读到数据为null的问题
这篇文章主要介绍了mybatis foreach遍历LIST读到数据为null的问题,具有很好的参考价值,希望对大家有所帮助。2022-02-02SpringBoot WebSocket实时监控异常的详细流程
最近做了一个需求,消防的设备巡检,如果巡检发现异常,通过手机端提交,后台的实时监控页面实时获取到该设备的信息及位置,然后安排员工去处理。这篇文章主要介绍了SpringBoot WebSocket实时监控异常的全过程,感兴趣的朋友一起看看吧2021-10-10
最新评论