Jackson Convert Object to Map Save Date Type

I am using Jackson ObjectMapper to convert Java Bean to Map .

However, it does not save the Date object, but converts to Long .

Here is a bad test case,

 @Test public void testObjectToMapDate() { User user = new User(); user.setDob(new Date()); ObjectMapper mapper = new ObjectMapper(); Map<String, Object> map = mapper.convertValue(user, Map.class); assertTrue(map.get("dob") instanceof Date); } 

Is there a simple solution?

+4
java json jackson
source share
1 answer

Jackson serializes java.util.Date instances as numerical timestamps by default. You can set Jackson to use text representation with

 mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); // it true by default 

or provide your own JsonSerializer .

However, when you perform the conversion, the intermediate JSON and the target type do not have a Map to tell Jackson that he should deserialize him as a Date object. Without additional type information, Jackson will always deserialize it using its default values ​​( long , double , String , LinkedHashMap ).

+7
source share

All Articles