List of subclasses and serialization of Jackson JSON

I have a small POJO containing ArrayList ( items), String ( title) and Integer ( id). Due to the fact that this is an Object, I have to: a) implement my own methods for wrapping around the methods of the List interface for the "items" property or b) make it itemspublicly available (a lot of things happen with this list).

Edit: to make the above point clearer, I need to access the list after deserialization to perform add / remove / get / etc operations - this means that I need to either write packaging methods in my class or make the List publication open, neither which I want to do about.

To avoid this, I just want to extend the ArrayList, but I cannot get it to work with Jackson. For some JSON, like this:

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

I want to deserialize titlein a field title, similar to for id, however I want to then populate my class with a class items.

Something 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 tried several ways to implement this, and everything fell, even things like:

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

Am I trying to do what cannot be done with Jackson?

+4
source share
1 answer

Can use the following pattern?

  • @JsonCreator neatly creates your object as indicated by the provided JSON.
  • Properties are set through @JsonPropertyannotations - they work both for serialization and for deserialization
  • ArrayList .

@JsonFormat . mapper NOT - .

@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;
    }
}
+6

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


All Articles