在Jackson2.11中,LocalDataTime格式在序列化过程中发生了变化。我对反序列化有问题。我找到了覆盖objectMapper配置的解决方案,如下面所示:
@Configuration
public class AppConfig {
@Bean
public ObjectMapper objectMapper()
{
ObjectMapper mapper = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
mapper.registerModule(javaTimeModule);
return mapper;
}但是,我仍然存在将json字符串反序列化到java模型的问题:
@Data
public class CustomLocalDataTime {
//@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSxxx") <- not working
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS") // <- not working
// @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", shape = JsonFormat.Shape.STRING) <- not working
private LocalDateTime date;
}因此,我从一些格式的响应localdatatime中接收到:2022-0405T05:00:00.000+00:00,在反序列化过程中,我仍然收到错误:
com.fasterxml.jackson.databind.exc.InvalidFormatException:
Cannot deserialize value of type `java.time.LocalDateTime`
from String "2022-04-05T05:00:00.000+00:00": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2022-04-05T05:00:00.000+00:00'
could not be parsed, unparsed text found at index 23
at [Source: (String)"{"date":"2022-04-05T05:00:00.000+00:00"}"; line: 1, column: 9]我是通过这样的复制来收到这个错误的:
@PostConstruct
public void customDeserializeTest() {
String content =
"{\"date\":\"2022-04-05T05:00:00.000+00:00\"}";
try {
CustomLocalDataTime customLocalDataTime = objectMapper.readValue(content, CustomLocalDataTime.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}我也尝试过添加: com.fasterxml.jackson.databind.annotation。
@JsonDeserialize(using = LocalDateTimeDeserializer.class)但这也是行不通的。
非常感谢您的指导。
发布于 2022-03-09 06:39:59
错误数据类型
正如其他人所评论的,您使用的数据类型是错误的。
LocalDateTime类故意缺乏时区或与世界协调时相抵的任何概念。因此,这个类不能表示时间轴上的一个特定点--。这个班只代表一天的日期和时间,但我们不知道这个日期和时间是打算去日本东京、法国图卢兹还是美国俄亥俄州托莱多。
因此,LocalDateTime类不适合您的输入。
字符串输入:
2022-04-05T05:00:00.000+00:002022-04-05T05:00:00.000Z…这两种方法都代表了世界协调时所看到的一个时刻,与世界协调时的零小时-分-秒相抵消。第二部分末尾的Z是+00:00的标准ISO 8601缩写,发音为“祖鲁”。
Instant & OffsetDateTime
您可以将这两个输入解析为Instant对象或更灵活的OffsetDateTime对象。
这些输入字符串使用标准的ISO 8601格式。java.time类在解析/生成时默认使用这些格式。因此,不需要指定格式模式。
Instant instant = Instant.parse( "2022-04-05T05:00:00.000+00:00" ) ;
Instant instant2 = Instant.parse( "2022-04-05T05:00:00.000Z" ) ;
OffsetDateTime odt = OffsetDateTime.parse( "2022-04-05T05:00:00.000+00:00" ) ;
OffsetDateTime odt2 = OffsetDateTime.parse( "2022-04-05T05:00:00.000Z" ) ;instant: 2022-04-05T05:00:00Z
instant2: 2022-04-05T05:00:00Z
odt: 2022-04-05T05:00Z
odt2: 2022-04-05T05:00Z有一条评论提到了使用ZonedDateTime。这样做是不明智的。时区具有Continent/Region格式的名称,如Europe/Paris或Pacific/Auckland。您的输入只有偏移量,没有时区。因此,ZonedDateTime在这里会产生误导和混淆。
偏移量仅仅是比世界协调时的主要子午线提前几个小时-分钟-秒。时区更重要。时区是对特定地区人民使用的偏移量的过去、现在和未来变化的命名历史。
https://stackoverflow.com/questions/71402341
复制相似问题