I am trying to get a map from the object using Jackson ObjectMapper:
ObjectMapper oMapper = ObjectMapperWithDate.getObjectMapper();
Map<String, Object> map = oMapper.convertValue(obj, Map.class);
I have problems with Date fields, for in the map they are becoming Long objects.
I have added de/serializers, as in ObjectMapper changes Date to String
public class ObjectMapperWithDate {
@Bean
public static ObjectMapper getObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.registerModule(
new SimpleModule("foo")
.addDeserializer(Date.class, new DateDeserializer())
.addSerializer(Date.class, new DateSerializer())
);
return mapper;
}
public static class DateSerializer extends StdScalarSerializer<Date> {
public DateSerializer() {
super(Date.class);
}
@Override
public void serialize(Date value, JsonGenerator gen, SerializerProvider provider)
throws IOException {
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
String output = formatter.format(value);
gen.writeString(output);
}
}
public static class DateDeserializer extends StdScalarDeserializer<Date> {
public DateDeserializer() {
super(Date.class);
}
@Override
public Date deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException {
try {
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
return formatter.parse(p.getValueAsString());
} catch (Exception e) {
return null;
}
}
}
}
Of course, the call for the mapper looks a bit different:
ObjectMapper oMapper = ObjectMapperWithDate.getObjectMapper();
Map<String, Object> map = oMapper.convertValue(obj, Map.class);
Now the Date objects become String object in the map. With the dates properly represented in them. But I need them to remain to be of the Date type. What is interesting, if I put breakpoints in the deserialiser, it is never reached. So, the deserializer is never reached, I think, it is because the mapper after serializing makes Date a String or a Long, depending on SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, and never recognizes the Date's in the time of deserialization.
How can I let Date properties remain Date ones after mapping? I need them to be recognized.
BTW, the BigDecimal properties are turned into Double ones. It seems to be the similar problem, but these two types are not of much difference to my further work.