杰克逊将对象转换为地图保留日期类型

杰克逊将对象转换为地图保留日期类型

本文介绍了杰克逊将对象转换为地图保留日期类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Jackson ObjectMapper 将 Java Bean 转换为 Map.

I am using Jackson ObjectMapper to convert a Java Bean to a Map.

然而,它不会保留 Date 对象,而是将其转换为 Long.

However, it is not preserving the Date object, rather it gets converted to Long.

这是失败的测试用例,

@Test
public void testObjectToMapDate() {

    User user = new User();
    user.setDob(new Date());

    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = mapper.convertValue(user, Map.class);
    assertTrue(map.get("dob") instanceof Date);

}

有没有简单的解决方法?

Is there a simple solution to this?

推荐答案

Jackson 默认将 java.util.Date 实例序列化为数字时间戳.您可以将 Jackson 配置为使用文本表示形式

Jackson, by default, serializes java.util.Date instances as numeric timestamps. You can configure Jackson to use a textual representation with

mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); // it's true by default

或提供您自己的JsonSerializer.

但是,当您进行转换时,中间 JSON 和目标类型 Map 中绝对没有任何内容向 Jackson 表明它应该将其反序列化为 Date 对象.如果没有额外的类型信息,Jackson 将始终使用其默认值(longdoubleStringLinkedHashMap)反序列化它.

However, when you are doing the conversion, there is absolutely nothing in the intermediate JSON and in the target type, Map, to indicate to Jackson that it should deserialize it as a Date object. Without extra type information, Jackson will always deserialize it using its defaults (long, double, String, LinkedHashMap).

这篇关于杰克逊将对象转换为地图保留日期类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 22:56