Error: Java 8 date/time type** java.time.Instant** not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310

I have followed forum comments and added relevant dependencies and mapper, but couldn't resolve issue.

Please advise me are there any annotations to resolve issue like we have @JsonDeserialize(using = LocalDateDeserializer.class) for java.time.LocalDate

Added dependencies for Jackson library as suggested in this forum

My input will be like this for Instant field: 2022-01-21T18:38:55Z

@Bean 
ObjectMapper objectMapper() { 
  ObjectMapper objectMapper = new ObjectMapper(); 
  objectMapper.registerModule(new JavaTimeModule()); 
  return objectMapper; 
}
2

There are 2 best solutions below

0
Coder On

Add this in the code for creating an object mapper bean

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.findAndRegisterModules();

More details in this post

0
mnfsd On

I have resolved this issue by adding DefaultInstantSerializer and DefaultInstantDeserializer classes and wrap with respective Serializer and Deserializer classes. the code below will help you to solve this issue and annotate java.time.Instant variables with these default classes.

1.

public class DefaultInstantSerializer extends InstantSerializer { 
    public DefaultInstantSerializer() {
        super(InstantSerializer.INSTANCE, false, false, 
            new DateTimeFormatterBuilder().appendInstant(3).toFormatter());
    }
}
public class DefaultInstantDeserializer extends InstantDeserializer<Instant> {
    public DefaultInstantDeserializer() {
        super(Instant.class, DateTimeFormatter.ISO_INSTANT,
            Instant::from,
            a -> Instant.ofEpochMilli(a.value), 
            a -> Instant.ofEpochSecond(a.integer, a.fraction),
            null,true);
    }
}

Usage:

public class SomeModel {
   // Other fields

   JsonDeserialize(using= DefaultInstantDeserializer.class)
   JsonSerialize(using = DefaultInstantSerializer.class)
   private Instant instant;
}