I am serializing an instance of a class with Jackson.
What is the best way to only serialize the fields of the superclass of this instance?
Currently I have to add the JSONIgnore annotation to every method in my subclass,
is there any better way to do that?
Assuming you have control of the serialization process directly via
ObjectMapper, you can easily accomplish this by creating an ObjectWriter specific to your superclass. Here is some sample code illustrating this.Running the above code illustrates that Jackson writes the superclass fields, even though the runtime instance is of the subclass type.
EDIT:
This scenario is even easier to deal with. Just annotate the appropriate fields in the outer class with @JsonSerialize. If you declare the fields as the superclass type, then set the
typingas static. This will flag those fields to Jackson to be serialized using the compile time type as opposed to the runtime type.On the other hand, if you declare the fields as the subclass type, then set the
usingas the superclass.The following example uses the classes I defined further above: