Jackson JSON 序列化,通过级别定义避免递归 [英] Jackson JSON serialization, recursion avoidance by level defining
问题描述
我使用 Jackson 库将我的 pojo 对象序列化为 JSON
表示.例如我有 A 类和 B 类:
I use Jackson library for serialization of my pojo objects into JSON
representation.
For example I have class A and class B:
class A {
private int id;
private B b;
constructors...
getters and setters
}
class B {
private int ind;
private A a;
constructors...
getters and setters
}
如果我想从 A 类序列化对象,那么在序列化时有一定的可能会得到递归.我知道我可以通过使用 @JsonIgnore
来阻止它.
If I want to serialize object from class A there is certain possibility to get recursion while it is serialized. I know i can stop it by using @JsonIgnore
.
是否可以通过深度级别限制序列化?
比如如果级别是2,序列化会这样:
For example, if the level is 2, the serialization will go this way:
- 序列化a, level = 0 (0 <2 ok) - > 序列化
- 序列化a.b,级别=1(1 <2 ok) -> 序列化
- 序列化 a.b.a, level = 2 (2 < 2 not true) ->停止
提前致谢.
推荐答案
我最近遇到了类似的问题:Jackson - 具有双向关系的实体的序列化(避免循环)
I recently encountered a similar problem: Jackson - serialization of entities with birectional relationships (avoiding cycles)
所以解决方案是升级到Jackson 2.0,并在类中添加以下注释:
So the solution is to upgrade to Jackson 2.0, and add to classes the following annotation:
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class,
property = "@id")
public class SomeEntityClass ...
这很完美.
这篇关于Jackson JSON 序列化,通过级别定义避免递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!