Jackson Cannot deserialize value of type `xxx` from String “xxx“ : Failed to deserialize xxx问题解决

妖狐艹你老母 2023-09-29 14:58 148阅读 0赞

问题描述:

com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDateTime` from String “2022-05-18 11:35:35”: Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text ‘2022-05-18 11:35:35’ could not be parsed at index 10
at [Source: (String)”{“localDate”:”2022-05-18”,”localDateStr”:null,”localDateTime”:”2022-05-18 11:35:35”,”localDateTimeStr”:null}“; line: 1, column: 63] (through reference chain: com.xudongbase.common.model.TestModel[“localDateTime”])

问题分析:

1、由于yyyy-MM-dd HH:mm:ss 格式的String数据不能转换LocalDateTime类型数据,导致报错。

  1. /**
  2. * 测试单个实体反序列化和反序列化
  3. */
  4. @Test
  5. public void testModelSerializeAndDeserialize() throws Exception {
  6. TestModel testModel = new TestModel();
  7. testModel.setLocalDate(LocalDate.now());
  8. testModel.setLocalDateTime(LocalDateTime.now());
  9. String jsonStr = objectMapper.writeValueAsString(testModel);
  10. testModel = objectMapper.readValue(objectMapper.getFactory().createParser(jsonStr),TestModel.class);
  11. }

解决办法:LocalDateTime类型变量添加@JsonFormat注解指定日期格式即可。

  1. @Data
  2. public class TestModel {
  3. private LocalDate localDate;
  4. private String localDateStr;
  5. @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
  6. private LocalDateTime localDateTime;
  7. private String localDateTimeStr;
  8. }

发表评论

表情:
评论列表 (有 0 条评论,148人围观)

还没有评论,来说两句吧...

相关阅读