java - 子类化列表和 Jackson JSON 序列化

标签 java json serialization jackson

我有一个小型 POJO,包含一个 ArrayList (items)、一个 String (title) 和一个 Integer (id)。由于这是一个对象,我必须 a) 围绕“items”属性的 List 接口(interface)方法实现我自己的包装方法,或者 b) 公开 items(很多事情发生在那个列表)。

编辑:为了让上面的点更清楚,我需要在反序列化后访问List 执行添加/删除/获取/等操作 - 这意味着我要么需要在我的类中编写包装方法,要么将列表公开,我都不想这样做。

为了避免这种情况,我只想直接扩展 ArrayList,但我似乎无法让它与 Jackson 一起工作。给定一些像这样的 JSON:

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

我想将 title 反序列化到 title 字段中,对于 id 也是如此,但是我想然后用 项目

看起来像这样的东西:

public class myClass extends ArrayList<Integer> {

    private String title;
    private Integer id;

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

}

我尝试了几种方法来实现这个,但都失败了,甚至是:

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

我想要完成的事情仅仅是 Jackson 无法完成的事情吗?

最佳答案

下面的模式有用吗?

  • @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;
    }
}

关于java - 子类化列表和 Jackson JSON 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27651394/

相关文章:

python - 如何在 PyTorch 中保存经过训练的模型?

java - 如何在Play框架中添加请求过滤器?

java - 继承困惑 - 在构造函数中打印时值为 "this"

java - 创建 JSONObject 时如何避免在字符串值周围加上引号

json - 如何在 React 中使用 JSON 对象

c# - 将 JSON 反序列化为字符串

c# - 如何将 XML 反序列化为 json 和将 json 反序列化为 c# 类?

java - 如何修改实体管理器的查询缓存?

java - RMI ClassCastException 到远程接口(interface)

php - Web服务API设计中哪种schema更好