Inheriting @JsonCreator annotations from a superclass

I have a number of objects with a set of common properties in a superclass:

public Superclass { int id; String name; ... } 

And I have subclasses that inherit from the superclass, but each one needs its own fully described @JsonCreator

 public Subclass1 extends Superclass { String color; @JsonCreator public Subclass1(@JsonProperty("id") int id, @JsonProperty("name") String name, @JsonProperty("color") String color) { super(id, name); this.color = color; } } public Subclass2 extends Superclass { int height; @JsonCreator public Subclass1(@JsonProperty("id") int id, @JsonProperty("name") String name, @JsonProperty("height") int height) { super(id, name); this.height = height; } } 

Is there a way for Jackson (2.x) to extract information from the superclass regarding the expected JSON fields and avoid this repetition?

+4
source share
1 answer

Since your classes do not seem immutable, you can put @JsonSetter annotations in the setter methods in the base class for the "id" and "name" properties. Then deserialization will create the appropriate subtype and will use setters instead of the constructor.

 public class Superclass { private int id; private String name; @JsonSetter public void setId(int id) { ... } @JsonSetter public void setName(String name) { ... } } public Subclass1 extends Superclass { private String color; @JsonSetter public void setColor(String color) { ... } } public Subclass2 extends Superclass { private int height; @JsonSetter public void setHeight(int height) { ... } } 

You may also be able to use @JsonSubTypes. This annotation will be translated into the Superclass, and you will have to list the links for each subtype (Subclass1 and Subclass2). I don’t know, from my point of view, if this allows you to use @JsonCreator in a superclass to avoid duplicate properties of β€œid” and β€œname” in subclasses, but I find it worth a try. The downside of this approach is that your base class has explicit subtype references.

+2
source

Source: https://habr.com/ru/post/1490296/


All Articles