Adnan Abdul Khaliq
Adnan Abdul Khaliq

Reputation: 495

Jackson Object Mapper com.fasterxml.jackson.databind.exc.MismatchedInputException

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!

Upvotes: 1

Views: 1466

Answers (1)

Julien
Julien

Reputation: 2246

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

Upvotes: 3

Related Questions