拥有这样的类
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public final class ActiveRecoveryProcess {
private UUID recoveryId;
private Instant startedAt;
}
我得到的是带有消息Cannot deserialize value of type
java.time.Instantfrom 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
的com.fasterxml.jackson.databind.exc.InvalidFormatException
JSON输入
{"startedAt": "2020-02-22T16:37:23", "recoveryId": "6f6ee3e5-51c7-496a-b845-1c647a64021e"}
Jackson配置
@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
)
其中CCD_ 4是TIMESTAMP。
您试图解析的字符串,22020-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")));
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;