![](/img/trans.png)
[英]How to deserialize java.time.Instant in Jackson2JsonRedisSerializer
[英]Cannot deserialize value of type `java.time.Instant` - jackson
有這樣的課
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public final class ActiveRecoveryProcess {
private UUID recoveryId;
private Instant startedAt;
}
我收到com.fasterxml.jackson.databind.exc.InvalidFormatException
消息Cannot deserialize value of type
java.time.Instant Cannot deserialize value of type
值from String "2020-02-22T16:37:23": Failed to deserialize java.time.Instant: (java.time.format.DateTimeParseException) Text '2020-02-22T16:37:23' could not be parsed at index 19
JSON 輸入
{"startedAt": "2020-02-22T16:37:23", "recoveryId": "6f6ee3e5-51c7-496a-b845-1c647a64021e"}
傑克遜配置
@Autowired
void configureObjectMapper(final ObjectMapper mapper) {
mapper.registerModule(new ParameterNamesModule())
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule());
mapper.findAndRegisterModules();
}
編輯
JSON 是從 postgres 生成的
jsonb_build_object(
'recoveryId', r.recovery_id,
'startedAt', r.started_at
)
其中r.started_at
是時間戳。
一種方法是創建一個Converter
。
public final class NoUTCInstant implements Converter<LocalDateTime, Instant> {
@Override
public Instant convert(LocalDateTime value) {
return value.toInstant(ZoneOffset.UTC);
}
@Override
public JavaType getInputType(TypeFactory typeFactory) {
return typeFactory.constructType(LocalDateTime.class);
}
@Override
public JavaType getOutputType(TypeFactory typeFactory) {
return typeFactory.constructType(Instant.class);
}
}
然后注釋該字段。
@JsonDeserialize(converter = NoUTCInstant.class)
private Instant startedAt;
您嘗試解析的字符串2020-02-22T16:37:23不以Z結尾。 Instant 期望這一點,因為它代表UTC 。 它根本無法解析。 將字符串與 Z 連接以解決該問題。
String customInstant = "2020-02-22T16:37:23";
System.out.println("Instant of: " + Instant.parse(customInstant.concat("Z")));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.