我正在尝试使用Jackson ObjectMappper将Java POJO转换为Map。但是,转换时,日期更改为字符串。
这是我的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;
}
}
这是我的代码:
@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;
}
我知道这已经有可能的答案here。但是我的ObjectMapper已经以相同的方式配置,但仍然无法正常工作。
这是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;
}
答案 0 :(得分:1)
在日期方面,我通常会像这样创建自己的自定义序列化器和反序列化器。这应该可以解决您的问题。
@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;
}
然后有2种用于反序列化和序列化的静态方法:
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;
}
}
}