jackson-modules-java8
jackson-modules-java8 copied to clipboard
Cannot read Optionals written with StdTypeResolverBuilder
The following test fails on Jackson 2.9.7 and passes on 2.8.11:
@Test
public void test() throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.setDefaultTyping(
new StdTypeResolverBuilder()
.init(JsonTypeInfo.Id.CLASS, null)
.inclusion(JsonTypeInfo.As.WRAPPER_OBJECT)
);
mapper.registerModule(new Jdk8Module());
String json = mapper.writeValueAsString(new Foo(Optional.of(1)));
System.out.println(json);
mapper.readValue(json, Foo.class);
}
public static class Foo {
private Optional<Integer> bar;
public Foo() {
}
public Foo(Optional<Integer> bar) {
this.bar = bar;
}
public Optional<Integer> getBar() {
return bar;
}
public void setBar(Optional<Integer> bar) {
this.bar = bar;
}
}
Complete runnable project with this test-case can be found on https://github.com/isopov/jackson-optional-test
Added workaround, involving copy&pasting classes from 2.8.11 - https://github.com/isopov/jackson-optional-test/blob/workaround/src/test/java/com/example/OptionalJacksonTest.java
Still proper fix will be highly appreciated.
I will have to say that it is quite possible that combination of polymorphic type in Optional for root value may be unsupportable. I would strongly recommend not using that combination: partly since root values have significant challenges wrt type erasure, and partly as Optionals are challenging in their own right.
In fact I am considering adding a warning that polymorphic type handling is not recommended to be used for root values at all.
Having said that: I will try to figure out if this can be made to work correctly (although depending on changes they might only be made to 2.9 branch), and I hope this is the case.
Thank you for reporting the problem.
EDIT Looking at this further, Optional is NOT used as root value. So that's not the problem.
To help future work, output looks like:
{"com.fasterxml.jackson.datatype.jdk8.PolymorphicOptionalTest$Foo":{"bar":1}}
and that would seem to be missing type information for contents, somehow.