gpt4 book ai didi

java - ObjectMapper 将日期更改为字符串

转载 作者:行者123 更新时间:2023-12-02 10:20:51 26 4
gpt4 key购买 nike

我正在尝试使用 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;
}

最佳答案

当涉及到日期时,我通常会像这样创建自己的自定义序列化器和反序列化器。这应该可以解决你的问题。

@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;
}
}
}

关于java - ObjectMapper 将日期更改为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54352027/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com