Is it possible to specify to the value serializer that an object should be serialized as a specific type knowing its runtime information? #136
Unanswered
WannabeSoftwareEngineer
asked this question in
Q&A
Replies: 1 comment 2 replies
-
I am not sure I fully understand the question but:
But as to the thing you are trying to achieve: if you want to just exclude some properties on sub-classes, maybe simple |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi all,
I would like to know if it is possible to specify to the value serializer that an object should be serialized as one of its supertypes (not necessary a direct ancestor) according to its runtime type and custom annotations.
The class that needs to be serialized has this form:
The chain of inheritance looks as follow:
Animal <- Bird <- Parrot
Animal <- Fish
and the object that needs to be serialized is:
What I would like for the serializer to do is to serialize the
myFarm.animal
as aBird
(closest ancestor ofParrot
) rather thanParrot
, so the output JSON should not have the fieldlatinName
in it.What I would like to know if it is possible for me to tell to the serializer the type that the object should be serialized as, knowing its runtime type and not its declared type (i.e.,
Parrot
and notAnimal
)Constraints
CustomAnnotation
, so I need to find the closest ancestorJsonTypeInfo
andJsonSubTypes
because I need to support thisCustomAnnotation
in my applicationType information
For the type information, I implemented a custom
TypeIdResolver
that maps the runtime type of the object to one of the subtypes defined inCustomAnnotation
.Solution that I already attempted
CustomAnnotationIntrospector extends NopAnnotationIntrospector
class, and I overrode this methodProblem: the
baseType
is always the declared type, i.e.Animal
, and not the runtime typeResearch I have done
JsonSerialize(as = ...)
JsonTypeInfo
andJsonSubTypes
) in order to see what is the default behavior. What I got as output JSON was the fullParrot
, even tough I defined inJsonSubTypes
onlyFish
andBird
. The type indicator property assumes whatever value you get from the method you defined inJsonTypeInfo
.Beta Was this translation helpful? Give feedback.
All reactions