Search code examples
javaserializationjacksonobjectmapper

Deserialize Instant.ofEpochSecond() object format to Instant?


I have a following model defined

public class ItemDetail {
    private final String name;
    private final String id;
    private final Instant someDate;
}

I am setting someDate as setSomeDate(Instant.ofEpochSecond(resultSet.getLong("someDate")). I am reading this from a database.

I am serializing this model to return the following response where someDate is assigned Instant.ofEpochSecond()

{
  "name": "Some nights",
  "id": "XYZZ01AS",
  "someDate": {
        "nano": 0,
        "epochSecond": 1292486400
    }
}

My client code parses this response and I am fine with the output.

Now, I want to test this and would like to deserialize this response in my tests. Assuming the above response is stored in the response variable.

String response = ..... //string containing json response same as above format 
ItemDetail itemDetail = objectMapper.readValue(response, ItemDetail.class);

This doesn't work even after registering the new ObjectMapper().registerModule(new JavaTimeModule()) (obvious). It throws the following error

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 

Is there anyway to make this work without implementing the custom deserializer?

Note: I just want to do this as part of the tests and don't intend to make any changes to the defined model ItemDetail.


Solution

  • JavaTimeModule should be active during serialization new ObjectMapper().registerModule(new JavaTimeModule()); . Otherwise the Objectmapper will convert Instant datatype to a nested object with epochSecond and nano