Tagged unions generated for Jackson @JsonTypeInfo with EXISTING_PROPERTY #582
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This change is expansion of tagged (discriminated) union feature introduced in #81. It adds support for Jackson polymorphic types discriminated by
EXISTING_PROPERTY
.Already supported is
PROPERTY
variant of Jackson polymorphic types but there are issues with it. In this case Jackson adds discriminant property when serializing sub-class and uses this additional property to deserialize JSON object to correct Java sub-class. But this mechanism doesn't work in cases where type information is not available to Jackson. For example when passingList
of such objects directly to Jackson likenew ObjectMapper().writeValueAsString(List.of(new SomeSubClass()))
then specifiedPROPERTY
is not included. Another case where this mechanism doesn't work is Spring REST controller where return type of some method contains such class wrapped in generic class, for exampleOptional<T>
, like this@GetMapping Optional<SomeRootClass> test() { return Optional.of(new SomeSubClass()); }
.Since using
PROPERTY
causes described issue it is now supported to use variant withEXISTING_PROPERTY
. In this variant Jackson uses value of regular (existing) property when serializing those objects but it uses annotations when deserializing them. So it can be inconsistent. However it is possible to mitigate this disadvantage and get reasonable level of confidence. For example we can havefinal
field filled in mandatory constructor call and use constants like this:Or we could reuse values from annotations for example like this:
Both examples have, of course, their pros and cons.