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;

总结

  1. SpringBoot的Jackson默认支持的时间类型为Date,配置application.properties文件里的全局配置只对Date生效
  2. @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") 只能解决Controller方法入参和返回对象的LocalDateTime,对ObjectMapper操作对象无效
  3. 需要配置LocalDateTime的序列化器和反序列化器
posted @ 2022-06-15 21:17  liuyiyuan  阅读(10261)  评论(0编辑  收藏  举报