【问题标题】:Subclassing List and Jackson JSON serialization子类化列表和杰克逊 JSON 序列化
【发布时间】:2015-02-23 10:15:17
【问题描述】:

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

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

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

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

我想将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

}

我尝试了几种方法来实现这一点,但都失败了,即使是这样的事情:

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

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

【问题讨论】:

    标签: java json serialization jackson


    【解决方案1】:

    以下模式有用吗?

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

    【讨论】:

    • 哇哦,太好了!我有类似的东西,但我不知道@JsonFormat。我会试一试上述情况并报告。
    • 这很好用,感谢@JsonFormat 的提示,我在浏览文档之前/时从未见过它使用过。
    猜你喜欢
    • 2013-05-20
    • 2016-07-16
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多