7

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

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

And I have subclasses which inherit from the superclass but each of them need their 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 any way for Jackson (2.x) to pull information from the superclass regarding expected JSON fields and to avoid this repetition?

1 Answers1

2

Since your classes do not appear to be immutable you could put @JsonSetter annotations on setter methods in the base class for the "id" and "name" properties. Then deserialization will create the appropriate subtype and use the setters instead of a 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 might be able to use @JsonSubTypes as well. This annotation would go on Superclass and you would have to list references to each subtype (Subclass1 and Subclass2). I don't know off the top of my head if this would allow you to leverage a @JsonCreator in Superclass to avoid repeating the "id" and "name" properties in the subclasses but I figure it's worth a try. The down side of this approach is that your base class has explicit references to subtypes.

Erik Gillespie
  • 3,929
  • 2
  • 31
  • 48