Subclassing List和Jackson JSON序列化

whi*_*fin 5 java serialization json jackson

我有一个小的POJO,包含一个ArrayList(items),一个String(title)和一个Integer(id).由于这是一个Object,我必须a)围绕"items"属性的List接口方法实现我自己的包装方法,或者b)items公开(很多东西都发生在该列表中).

编辑:为了使上述观点更加清晰,我需要在反序列化后访问List来执行add/remove/get/etc操作 - 这意味着我要么在我的类中编写包装方法,要么将List公之于众,这两者都不是我的想做.

为了避免这种情况,我想直接扩展ArrayList,但是我似乎无法与Jackson合作.给出一些像这样的JSON:

{ "title": "my-title", "id": 15, "items": [ 1, 2, 3 ] }
Run Code Online (Sandbox Code Playgroud)

我想反序列化title到这个title领域,同样的id,但是我想用我的类来填充我的班级items.

看起来像这样的东西:

public class myClass extends ArrayList<Integer> {

    private String title;
    private Integer id;

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

}
Run Code Online (Sandbox Code Playgroud)

我尝试了几种方法来实现这一点,所有这些都坍塌了,甚至包括:

private ArrayList<Integer> items = this; // total long shot
Run Code Online (Sandbox Code Playgroud)

我想要完成的只是杰克逊无法做到的事情吗?

was*_*ren 7

可以使用以下模式吗?

  • @JsonCreator由提供JSON指定整齐地创建你的对象.
  • 属性通过@JsonProperty注释指定- 适用于序列化和反序列化
  • 您可以ArrayList根据您的要求继承

魔术位于指定@JsonFormat的第一行.它指示对象映射器将此对象视为集合或数组 - 只需将其视为对象即可.

@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;
    }
}
Run Code Online (Sandbox Code Playgroud)