-1

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; 
}
Coder
  • 6,948
  • 13
  • 56
  • 86
mnfsd
  • 1
  • 2
  • 1
    Please provide a [mre]. Specifically, which libraries you have on the classpath, how you initialize your object mapper, the code you use and the exact exception stacktrace. – Mark Rotteveel Feb 27 '23 at 16:56
  • Added this mapper: @Bean ObjectMapper objectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new JavaTimeModule()); return objectMapper; } and added depencies: jackson-datatype-jdk8(2.11.3), jackson-datatype-jsr310(2.11.3) – mnfsd Feb 27 '23 at 17:21
  • 1
    Post details as edits to your Question, not as Comments. – Basil Bourque Feb 27 '23 at 22:22
  • Does this answer your question? [serialize/deserialize java 8 java.time with Jackson JSON mapper](https://stackoverflow.com/questions/27952472/serialize-deserialize-java-8-java-time-with-jackson-json-mapper) – Coder Feb 28 '23 at 12:15

2 Answers2

0

Add this in the code for creating an object mapper bean

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

More details in this post

Coder
  • 6,948
  • 13
  • 56
  • 86
0

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;
}
frmi
  • 508
  • 1
  • 7
  • 21
mnfsd
  • 1
  • 2