简体   繁体   中英

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

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 type java.time.Instant 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 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.

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;

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")));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM