Cannot deserialize value of type `java.time.Instant` - jackson

Viewed 10757

Having class like this

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

    private UUID recoveryId;
    private Instant startedAt;
}

I'm getting com.fasterxml.jackson.databind.exc.InvalidFormatException with message 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 input

{"startedAt": "2020-02-22T16:37:23", "recoveryId": "6f6ee3e5-51c7-496a-b845-1c647a64021e"}

Jackson configuration

    @Autowired
    void configureObjectMapper(final ObjectMapper mapper) {
        mapper.registerModule(new ParameterNamesModule())
                .registerModule(new Jdk8Module())
                .registerModule(new JavaTimeModule());
        mapper.findAndRegisterModules();
    }

EDIT

JSON is generated from postgres

jsonb_build_object(
                        'recoveryId', r.recovery_id,
                        'startedAt', r.started_at
)

where r.started_at is TIMESTAMP.

2 Answers

The String you're trying to parse, 2020-02-22T16:37:23, doesn't end in Z. Instant expects this as it stands for UTC. It simply cannot be parsed. Concat the String with Z to resolve the issue.

        String customInstant = "2020-02-22T16:37:23";

        System.out.println("Instant of: " + Instant.parse(customInstant.concat("Z")));

One way to do this is to create a 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);
    }
}

Then annotate the field.

@JsonDeserialize(converter = NoUTCInstant.class)
private Instant startedAt;
Related