ObjectMapper 将 Date 更改为 String



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

我知道这已经有一个可能的答案了。但是我的 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;
            }
        }
    }

相关内容

  • 没有找到相关文章

最新更新