Jackson JSON序列化,通过级别定义的递归避免 [英] Jackson JSON serialization, recursion avoidance by level defining

查看:663
本文介绍了Jackson JSON序列化,通过级别定义的递归避免的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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,等级= 0(0 <2 ok) - >序列化

  • 序列化ab,等级= 1
    (1 < 2 ok) - >序列化

  • 序列化aba,level = 2(2< 2不是真的) - >
    stop

提前致谢。

推荐答案

我最近遇到过类似的问题:杰克逊 - 具有双向关系的实体的序列化(避免周期)

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆