简体   繁体   中英

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!

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

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