jackson-databind icon indicating copy to clipboard operation
jackson-databind copied to clipboard

Workaround for combining @JsonUnwrapped and @JsonTypeInfo?

Open chris-dekker opened this issue 5 months ago • 3 comments

Search before asking

  • [X] I searched in the issues and found nothing similar.

Describe the bug

It is currently not possible to combine @JsonUnwrapped with generic types using @JsonTypeInfo

Version Information

2.17.2

Reproduction

I have a generic Versioned<T> type containing a int version() and a payload T item(). I'd like to be able to (de)serialize this using @JsonUnwrapped, but cannot seem to get this to work together with the necessary @JsonTypeInfo to deal with the generic types.

Take the following types

  public record Inner(String foo, int bar) {}

  public record Versioned<T>(
      int version,
      @JsonUnwrapped @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "@class") T item) {}

And the following example

    Versioned<Inner> example = new Versioned<>(1, new Inner("foo", 123));
    new ObjectMapper().writeValueAsString(example);

I would expect this produce the following JSON:

{
  "version": 1,
  "@class": "my.package.Inner",
  "foo": "foo",
  "bar": 123
}

But this does not work. Even when disabling SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS it still does drops the @class property, making deserialization fail.

Expected behavior

No response

Additional context

I found a bunch of threads from 10+ years ago where this was not supported through Jackson. I hope this has changed by now. It is not clear to me from this simple example why this is not supported.

Alternatively, I tried to create a manual StdSerializer and StdDeserializer but was unable to get the @JsonTypeInfo annotation to work. Any examples given would be great!

chris-dekker avatar Sep 13 '24 16:09 chris-dekker