且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何解决由休眠双向映射引起的json序列化程序中的循环引用?

更新时间:2022-11-02 18:53:52

双向关系甚至可以用JSON表示吗?某些数据格式不适合某些类型的数据建模。

在处理遍历对象图时处理周期的一种方法是跟踪目前为止您已经看到的对象(使用身份比较),以防止自己遍历无限循环。

I am writing a serializer to serialize POJO to JSON but stuck in circular reference problem. In hibernate bidirectional one-to-many relation, parent references child and child references back to parent and here my serializer dies. (see example code below)
How to break this cycle? Can we get owner tree of an object to see whether object itself exists somewhere in its own owner hierarchy? Any other way to find if the reference is going to be circular? or any other idea to resolve this problem?

Can a bi-directional relationship even be represented in JSON? Some data formats are not good fits for some types of data modelling.

One method for dealing with cycles when dealing with traversing object graphs is to keep track of which objects you've seen so far (using identity comparisons), to prevent yourself from traversing down an infinite cycle.