[英]Subclassing List and Jackson JSON serialization
I have a small POJO, containing an ArrayList ( items
), a String ( title
), and an Integer ( id
). 我有一个小的POJO,包含一个ArrayList( items
),一个String( title
)和一个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). 由于这是一个Object,我必须a)围绕“items”属性的List接口方法实现我自己的包装方法,或者b)将items
公开(该列表会发生很多事情)。
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. 编辑:为了使上述观点更加清晰,我需要在反序列化后访问List以执行添加/删除/获取/等操作 - 这意味着我需要在我的类中编写包装方法或将List公之于众,这两者都不是我的想做。
In order to avoid this, I want to just directly extend ArrayList, however I can't seem to get it to work with Jackson. 为了避免这种情况,我想直接扩展ArrayList,但是我似乎无法与Jackson合作。 Given some JSON like this: 给出一些像这样的JSON:
{ "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
. 我想反序列化title
到title
领域,同样的id
,但是我想然后填充我的课与的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? 我想要完成的只是杰克逊无法做到的事情吗?
Could the following pattern be of use? 可以使用以下模式吗?
@JsonCreator
neatly creates your object as specified by the provided JSON. @JsonCreator
根据提供的JSON指定整齐地创建对象。 @JsonProperty
annotations - work for both serialization and deserialization 属性通过@JsonProperty
注释指定 - 适用于序列化和反序列化 ArrayList
as per your requirements 您可以根据您的要求继承ArrayList
The magic lies in specifying the @JsonFormat
on the first line. 神奇之处在于在第一行指定@JsonFormat
。 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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.