0

Say I have the following class:

public class MyPojo {
    public ZonedDateTime now;
}

To convert a Map<String, Object> into this POJO, according to https://stackoverflow.com/a/16430704/1225328, ObjectMapper#convertValue can be used:

Map<String, Object> myMap = new HashMap<String, Object>(){{
    put("now", ZonedDateTime.now());
}};
ObjectMapper objectMapper = new ObjectMapper();
MyPojo myPojo = objectMapper.convertValue(myMap, MyPojo.class);

The above code fails though, with:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.ZonedDateTime` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)

I think Jackson first "deserialised" the map's ZonedDateTime value into a Map<String, Object>, and then tries to rebuild a ZonedDateTime instance from this generated map to set the POJO's now property.

I don't need something that smart; is there any way to tell Jackson "if you find a value in the input map that is of the same type of the POJO property whose name matches the key, then just set it and go on"?

sp00m
  • 47,968
  • 31
  • 142
  • 252
  • Maybe this can help... https://stackoverflow.com/questions/1301697/helper-in-order-to-copy-non-null-properties-from-object-to-another-java espeachially the option that uses a stream to copy entries – ernest_k Oct 22 '18 at 16:56

1 Answers1

0

You need to add the jackson-datatype-jsr310 library to your classpath and register the JavaTimeModule in your ObjectMapper in order to serialize/deserialize java.time Objects properly:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());

This will make your example work.

Stefan Ferstl
  • 5,135
  • 3
  • 33
  • 41