vavr-io / vavr-jackson

Jackson datatype module for Vavr
Apache License 2.0
99 stars 38 forks source link

EitherSerializer / EitherDeserializer does not respect default typing #132

Open kreed-rmn opened 5 years ago

kreed-rmn commented 5 years ago

If an object mapper is configured with default typing, for example,

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new VavrModule());
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);

a client cannot deserialize json without providing the explicit Either.class class type to the mapper's readValue method. In other words, the serialization mechanism is not including the type information if this is enabled.

A simple example, like so fails:

@Test
public void enabledDefaultTyping()
        throws IOException {
    ObjectMapper mapper = mapper();
    mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);

    Either<String, Integer> right = Either.right(1);
    String json = mapper().writer().writeValueAsString(right);

    System.out.println(json);

    // explicitly use Object.class here to have the mapper utilize
    // the default typing information included in serialization
    Either<String, Integer> restored = (Either<String, Integer>) mapper().readValue(json, Object.class);
    Assert.assertTrue(restored.isRight());
    Assert.assertEquals((long) restored.get(), 1);
}

with

java.lang.ClassCastException: class java.util.ArrayList cannot be cast to class io.vavr.control.Either (java.util.ArrayList is in module java.base of loader 'bootstrap'; io.vavr.control.Either is in unnamed module of loader 'app')

More complicated types can change this message.

The serialized value for the above code is ["right",1] which does not include the type information.

I'm currently working on a fix for this, but wanted to open this issue to bring it up. The context for this is that I'm using the GenericJackson2JsonRedisSerializer from spring-data-redis to serialize results to Redis using the @Cacheable mechanism from Spring. Some of the methods we cache return Either<.,.> and we'd like to be able to cache the results.

freerider7777 commented 11 months ago

Seems still not working