![](/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.