Jackson转换时间字符串为LocalDateTime类型报错解决
SpringBoot默认使用Jackson解析Json字符串
Controller方法参数有个LocalDateTime时间字段,数据格式为:2022-05-11 00:00:00
报错:
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.time.LocalDateTime` from String "2022-05-11 00:00:00": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2022-05-11 00:00:00' could not be parsed at index 10; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDateTime` from String "2022-05-11 00:00:00": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2022-05-11 00:00:00' could not be parsed at index 10<EOL> at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 15, column: 19] (through reference chain: cc.yuanspace.springboot.validator.vo.ValidVO["pastDateTime"])
序列化错误,字段上添加注解,解决
(application.properties中全局配置对LocalDateTime无效)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private LocalDateTime pastDateTime;
但是如果代码中使用Jackson操作对象时,如objectMapper.writeValueAsString(obj)
obj对象里有LocakDateTime类型字段
就又会报错:
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: cc.yuanspace.springboot.validator.vo.ValidVO["pastDateTime"]) at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:77) ~[jackson-databind-2.13.2.1.jar:2.13.2.1] at com.fasterxml.jackson.databind.SerializerProvider.reportBadDefinition(SerializerProvider.java:1300) ~[jackson-databind-2.13.2.1.jar:2.13.2.1]
说是默认情况下不支持java.time.LocalDateTime
怎么办,指定序列化器和反序列化器
@JsonDeserialize(using = LocalDateTimeDeserializer.class) @JsonSerialize(using = LocalDateTimeSerializer.class) @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private LocalDateTime pastDateTime;
总结
- SpringBoot的Jackson默认支持的时间类型为
Date
,配置application.properties
文件里的全局配置只对Date生效 @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
只能解决Controller
方法入参和返回对象的LocalDateTime
,对ObjectMapper操作对象无效- 需要配置LocalDateTime的序列化器和反序列化器
分类:
SpringBoot
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~