Reputation: 410
I am trying to use Jackson ObjectMappper to convert my Java POJO to Map. But, on converting, the Date changes to String.
This is my POJO:
public class Sample {
@Id
private String id;
private Date date;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
Here is my code:
@Test
public void testGenMap() {
Sample sample = new Sample();
sample.setId("a");
sample.setDate(new Date());
Map<String, Object> map = generateMap(sample);
System.out.println(map.get("date") instanceof Date); //false
}
private Map<String, Object> generateMap(Sample sample) {
Map<String, Object> map = CommonsContextUtil.getBean(ObjectMapper.class).convertValue(sample,Map.class);
map.values().removeIf(Objects::isNull);
return map;
}
I know this already has a possible answer here. But my ObjectMapper is already configured in the same way and still it is not working.
Here is the ObjectMapper Bean:
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper;
}
Upvotes: 2
Views: 5989
Reputation: 1082
When it comes to Dates, I usually create my own custom serializer and deserializer like so. This should solve your problem.
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
registerModule(
new SimpleModule("foo")
.addDeserializer(Date.class, new DateDeserializer())
.addSerializer(Date.class, new DateSerializer())
);
return mapper;
}
Then have 2 static methods for deserialization and serialization:
public static class DateSerializer extends StdScalarSerializer<Date> {
public DateSerializer() {
super(Date.class);
}
@Override
public void serialize(Date value, JsonGenerator gen, SerializerProvider provider)
throws IOException {
String output = value.toString();
gen.writeString(output);
}
}
public static class DateDeserializer extends StdScalarDeserializer<Date> {
public DateDeserializer() {
super(Date.class);
}
@Override
public LocalDate deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException {
try {
return Date.parse(p.getValueAsString());
} catch (Exception e) {
return null;
}
}
}
Upvotes: 4