我有一对像
public class Obj1 {
public int id;
public String name;
public Obj2 obj2;
}
public class Obj2 {
public int id;
public String name;
public List<Obj1> obj1list;
}
我希望能够通过 Jackson 将其转换为 Json。我找到了 JsonManagedReference
和 JsonBackReference
并对它们进行了注释,但是当您这样做时,序列化仅以一种方式工作。它只会在带有 JsonManagedReference
端的类被序列化时显示。
如果我序列化“Obj1”,我想查看附加到它的“Obj2”。如果我序列化“Obj2”,我想查看附加到它的“Obj1”列表。
我也试过像这样使用 JsonIdentityInfo 注释
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
这似乎有效,只是它将父对象的“id”值添加到子对象(或列表案例中的每个子对象)中,这有点奇怪。虽然我想我可以忍受。
有没有办法让它按照我的预期运行?
最佳答案
您正在查看 @JsonIgnoreProperties
,它将提供所需内容并避免 json 递归。
public class Obj1 {
public int id;
public String name;
@JsonIgnoreProperties("obj1list")
public Obj2 obj2;
}
public class Obj2 {
public int id;
public String name;
@JsonIgnoreProperties("obj2")
public List<Obj1> obj1list;
}
更新
我总是更喜欢 @JsonIgnoreProperties
而不是 JsonBackReference
和 JsonManagedReference
。因为它不仅可以解决问题,而且不会逃避任何数据序列化(这是此处需要的情况)。
我在 github 上也有一个示例项目处理这种情况。查找实体类代码 School.java
& District.java
。如果您想运行测试,它是一个 mvn spring-boot 可执行代码。
From Javadoc, starting with Jackson 2.0,
@JsonIgnoreProperties
annotation can be applied both to classes and to properties. If used for both, actual set will be union of all ignorals: that is, you can only add properties to ignore, not remove or override. So you can not remove properties to ignore using per-property annotation.
它是如何运作的
当您在属性级别定义@JsonIgnoreProperties
时,在序列化/反序列化时,它将对引用的属性对象起作用。
所以在这里,当Obj1
被解析时,你要求解析器忽略obj2
的obj1list
属性。类似地,在解析 Obj2
时,它将忽略 Obj
集合中包含的 obj2
引用。所以你的解析将如下所示:
Obj1 : {
id : int,
name : string,
Obj2 : {
id : int,
name : string
obj1list : //ignored avoids recursion
}
}
Obj2 : {
id : int,
name : string,
obj1list : [{
id : int,
name : string,
obj2 : //ignored avoids recursion
},
{
id : int,
name : string
obj2 : //ignored avoids recursion
}
]
}
关于java - Jackson json 双向对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50976307/