0
votes

[Related to Unexpected serialization behavior with configured Jackson ObjectMapper. I was asked to pose the question again.]

I am using Jackson 2.10.5 to serialize the same java.util.Date object twice.

The first time, with a basic Jackson ObjectMapper, I see the timestamp.

Then I construct a new ObjectMapper and configure it. I get a different result, the class name and the timestamp in a JSON list.

The configuration is intended to tell the ObjectMapper to include the class name of every object except java.util.Date as a JSON property.

Why is the Date object serialized differently between the two cases? Any advice how I am using the PolymorphicTypeMapper incorrectly would be appreciated.

The use case for this is as a JSON provider for Jersey. I have a way of generating and configuring an ObjectMapper at launch time, but the ability to configure per-write is just for the test code above.

Here's the test code:

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

        ObjectMapper om2 = new ObjectMapper();
        om2.activateDefaultTypingAsProperty(getPTV(), ObjectMapper.DefaultTyping.EVERYTHING, "@class");
        String serialized2 = om2.writeValueAsString(now); // result: ["java.util.Date",1605744866827]

        Logger.getLogger(SerializationTest.class).info(serialized1);
        Logger.getLogger(SerializationTest.class).info(serialized2);

        Assert.assertEquals("Unexpected change in serialization", serialized1, serialized2);

    } catch (JsonProcessingException e) {
        Assert.fail("Exception thrown: "+e);
    }
}

And here is the output:

INFO  2020-11-19 07:55:41,799 [main] <> test.SerializationTest : 1605801341571
INFO  2020-11-19 07:55:41,800 [main] <> test.SerializationTest : ["java.util.Date",1605801341571]

org.junit.ComparisonFailure: Unexpected change in serialization 
Expected :1605801341571
Actual   :["java.util.Date",1605801341571]
1

1 Answers

0
votes

This was a misunderstanding on my part.

The type validator is only refererenced for deserialization. It controls the classes that can be deserialized from their class information.