Home » Java » java – Jackson Object Mapper com.fasterxml.jackson.databind.exc.MismatchedInputException-Exceptionshub

java – Jackson Object Mapper com.fasterxml.jackson.databind.exc.MismatchedInputException-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am trying to run a following Junit test :

  @Test
  public void testObjectMapper() throws IOException {
    String json = new ObjectMapper().writeValueAsString(Instant.now());
    ObjectMapper om = new ObjectMapper()
        .registerModule(new JavaTimeModule())
        .configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
        .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        .configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
        .setSerializationInclusion(JsonInclude.Include.NON_NULL);
    om.readValue(json, Instant.class);
  }

But gets the following exception:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Unexpected token (START_OBJECT), expected one of [VALUE_STRING, VALUE_NUMBER_INT, VALUE_NUMBER_FLOAT] for java.time.Instant value
 at [Source: (String)"{"nano":627594000,"epochSecond":1581946138}"; line: 1, column: 1]

No idea why i am not able to deserialize (String)”{“nano”:627594000,”epochSecond”:1581946138}” into a Instant class.

Need help!

How to&Answers:

You should serialize your Instant with the same ObjectMapper used for the deserialization.

    ObjectMapper om = new ObjectMapper()
        .registerModule(new JavaTimeModule())
        .configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
        .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        .configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
        .setSerializationInclusion(JsonInclude.Include.NON_NULL);
    String json = om.writeValueAsString(Instant.now());
    om.readValue(json, Instant.class);