无法反序列化“java.time.Instant”类型的值 - jackson

hop*_*sey 7 java json jackson spring-boot

上这样的课

@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public final class ActiveRecoveryProcess {

    private UUID recoveryId;
    private Instant startedAt;
}
Run Code Online (Sandbox Code Playgroud)

我收到com.fasterxml.jackson.databind.exc.InvalidFormatException消息Cannot deserialize value of typejava.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

JSON 输入

{"startedAt": "2020-02-22T16:37:23", "recoveryId": "6f6ee3e5-51c7-496a-b845-1c647a64021e"}
Run Code Online (Sandbox Code Playgroud)

杰克逊配置

    @Autowired
    void configureObjectMapper(final ObjectMapper mapper) {
        mapper.registerModule(new ParameterNamesModule())
                .registerModule(new Jdk8Module())
                .registerModule(new JavaTimeModule());
        mapper.findAndRegisterModules();
    }
Run Code Online (Sandbox Code Playgroud)

编辑

JSON是从postgres生成的

jsonb_build_object(
                        'recoveryId', r.recovery_id,
                        'startedAt', r.started_at
)
Run Code Online (Sandbox Code Playgroud)

时间戳在哪里r.started_at

Jas*_*son 5

您尝试解析的字符串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")));
Run Code Online (Sandbox Code Playgroud)


And*_*eas 5

一种方法是创建一个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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后对该字段进行注释。

@JsonDeserialize(converter = NoUTCInstant.class)
private Instant startedAt;
Run Code Online (Sandbox Code Playgroud)