whitfin
whitfin

Reputation: 4629

Subclassing List and Jackson JSON serialization

I have a small POJO, containing an ArrayList (items), a String (title), and an Integer (id). Due to the fact that this is an Object, I have to a) implement my own wrapping methods around the List interface methods for the "items" property or b) make items public (lots of stuff happens with that list).

Edit: to make the above point clearer, I need to access the List after deserialisation to perform add/remove/get/etc operations - which means I either need to write wrapping methods in my class or make the List public, neither of which I want to do.

In order to avoid this, I want to just directly extend ArrayList, however I can't seem to get it to work with Jackson. Given some JSON like this:

{ "title": "my-title", "id": 15, "items": [ 1, 2, 3 ] }

I want to deserialize title into the title field, likewise for id, however I want to then populate my class with that of items.

Something that looks like this:

public class myClass extends ArrayList<Integer> {

    private String title;
    private Integer id;

    // myClass becomes populated with the elements of "items" in the JSON

}

I attempted several ways at implementing this and all fell down, even things such as:

private ArrayList<Integer> items = this; // total long shot

Is what I am trying to accomplish simply something which cannot be done with Jackson?

Upvotes: 5

Views: 2203

Answers (1)

wassgren
wassgren

Reputation: 19211

Could the following pattern be of use?

  • The @JsonCreator neatly creates your object as specified by the provided JSON.
  • The properties are specified via @JsonProperty annotations - work for both serialization and deserialization
  • you can inherit the ArrayList as per your requirements

The magic lies in specifying the @JsonFormat on the first line. It instructs the object mapper to NOT treat this object as a collection or array - simply treat it as an Object.

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public class MyList extends ArrayList<Integer> {
    private final Integer id;
    private final String title;

    @JsonCreator
    public MyList(@JsonProperty("id") final Integer id,
                  @JsonProperty("title") final String title,
                  @JsonProperty("items") final List<Integer> items) {
        super(items);
        this.id = id;
        this.title = title;
    }

    @JsonProperty("id")
    public Integer id() {
        return id;
    }

    @JsonProperty("items")
    public Integer[] items() {
        return this.toArray(new Integer[size()]);
    }

    @JsonProperty("title")
    public String title() {
        return title;
    }
}

Upvotes: 9

Related Questions