已配置Jackson ObjectMapper的java意外序列化行为
我正在使用Jackson 2.10.5将同一java.util.Date
对象序列化三次
- 第一次,用基本的Jackson
ObjectMapper
。我看到时间戳了李> - 然后配置相同的
ObjectMapper
,并重写。我得到了同样的结果李> - 然后我构造一个新的
ObjectMapper
,用同样的方式配置它。我得到了一个不同的结果,JSON列表中的类名和时间戳李>
该配置旨在告诉ObjectMapper
将每个对象的类名(除了java.util.Date
之外)包含为JSON属性
所以我有两个问题。第一个问题是,为什么在第三种情况下,日期对象的序列化方式不同?如有任何关于以不同方式使用PolymorphicTypeMapper
的建议,将不胜感激
第二个是为什么第一个和第二个是相同的(是因为对象映射器有一个缓存(哎哟!)?)
[编辑:我应该提到,这个用例是作为Jersey的JSON提供程序。我有一种在启动时生成和配置ObjectMapper
的方法,但是(in)配置每次写入的能力仅适用于上面的测试代码。]
private PolymorphicTypeValidator getPTV() {
return BasicPolymorphicTypeValidator.builder()
.denyForExactBaseType(Date.class)
.build();
}
@Test
public void serializationTest() {
try {
Date now = new Date();
// Create an object mapper and serialize the date
ObjectMapper om = new ObjectMapper();
String serialized1 = om.writeValueAsString(now); // result: 1605744866827
om.activateDefaultTypingAsProperty(getPTV(), ObjectMapper.DefaultTyping.EVERYTHING, "@class");
String serialized2 = om.writeValueAsString(now); // result: 1605744866827
ObjectMapper om2 = new ObjectMapper();
om2.activateDefaultTypingAsProperty(getPTV(), ObjectMapper.DefaultTyping.EVERYTHING, "@class");
String serialized3 = om2.writeValueAsString(now); // result: ["java.util.Date",1605744866827]
Logger.getLogger(SerializationTest.class).info(serialized1);
Logger.getLogger(SerializationTest.class).info(serialized2);
Logger.getLogger(SerializationTest.class).info(serialized3);
Assert.assertEquals("Unexpected change in serialization 1-2", serialized1, serialized2);
Assert.assertEquals("Unexpected change in serialization 1-3", serialized1, serialized3);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
以下是输出:
INFO 2020-11-18 16:14:27,065 [main] <> test.SerializationTest : 1605744866827
INFO 2020-11-18 16:14:27,066 [main] <> test.SerializationTest : 1605744866827
INFO 2020-11-18 16:14:27,066 [main] <> test.SerializationTest : ["java.util.Date",1605744866827]
org.junit.ComparisonFailure: Unexpected change in serialization 1-3
Expected :1605744866827
Actual :["java.util.Date",1605744866827]
# 1 楼答案
阅读文档,即^{} 的javadoc,上面写着(粗体我的亮点):