java - Jackson JSON序列化,通过级别定义避免递归

标签 java json serialization jackson

我使用 Jackson 库将我的 pojo 对象序列化为 JSON 表示。 例如我有 A 类和 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 来阻止它。

是否可以通过深度级别限制序列化?

例如,如果级别为2,则序列化会这样:

  • 序列化a,level = 0 (0 < 2 ok) -> 序列化
  • 序列化 a.b,级别 =1 (1 < 2 ok) -> 序列化
  • 序列化 a.b.a, level = 2 (2 < 2 not true) -> 停止

提前致谢。

最佳答案

我最近遇到了类似的问题:Jackson - serialization of entities with birectional relationships (避免循环)

所以解决方案是升级到 Jackson 2.0,并在类中添加以下注释:

@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, 
                  property = "@id")
public class SomeEntityClass ...

这很好用。

关于java - Jackson JSON序列化,通过级别定义避免递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10191671/

相关文章:

java - Axis 生成的 wsdl 不包含所有类型定义

json - Angular2 将字符串转换为 JSON

c# - 是否可以将 Protobuf-Net 与没有无参数构造函数的类一起使用?

c# - 在 .NET 中跨 AppDomains 移动对象

java - Google 云存储 - 监控文件更改

java - 如何加快查找 id 的循环速度

java - 异步调度程序错误

javascript - jQuery如何读取json缓存?

javascript - 无法从 JSON 获取嵌套对象

java - 生成 serialVersionID 而不是 1L、2L、