在使用Jackson序列化对象列表时,我想控制对象是否被序列化为“深”或“浅”。
例如:Test有两个X类对象列表
public class Test {
public List<X> list1;
public List<X> list2;
public Test() {
X x1 = new X("1", "one");
X x2 = new X("2", "two");
list1 = new LinkedList<X>();
list1.add(x1);
list1.add(x2);
list1.add(x1);
list2 = new LinkedList<X>();
list2.add(x1);
list2.add(x2);
}
}
public class X {
public String id;
public String name;
public X(String id, String name) {
this.id = id;
this.name = name;
}
}
如果序列化,它将如下所示:
{
"list1":[{"id":"1","name":"one"},{"id":"2","name":"two"},{"id":"1","name":"one"}],
"list2":[{"id":"1","name":"one"},{"id":"2","name":"two"}]
}
但是我想要序列化它,以便list1是X的浅版本,list2是X的深层版本:
{
"list1":["1","2","1"],
"list2":[{"id":"1","name":"one"},{"id":"2","name":"two"}]
}
杰克逊有没有注释会为我做这件事?自定义序列化可能吗?我能做些什么让我接近这个?
提前致谢!
答案 0 :(得分:0)
想出来(我想)。
public class Test {
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id") @JsonIdentityReference(alwaysAsId=true)
public List<X> list1;
public List<X> list2;