猿问

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

我正在编写一个序列化程序以将POJO序列化为JSON,但陷入循环引用问题。在休眠的双向一对多关系中,父级引用子级,而子级引用又回到父级,此时我的序列化程序死亡。(请参见下面的示例代码)
如何打破这个循环?我们可以获取对象的所有者树以查看对象本身是否存在于其所有者层次结构中的某个位置吗?还有其他方法可以找到参考是否为圆形吗?或任何其他想法来解决这个问题?

互换的青春
浏览 478回答 3
3回答

跃然一笑

我依靠Google JSON通过使用The feature处理此类问题从序列化和反序列化中排除字段假设A类和B类之间的双向关系如下public class A implements Serializable {&nbsp; &nbsp; private B b;}和Bpublic class B implements Serializable {&nbsp; &nbsp; private A a;}现在使用GsonBuilder来获取自定义Gson对象,如下所示(注意setExclusionStrategies方法)Gson gson = new GsonBuilder()&nbsp; &nbsp; .setExclusionStrategies(new ExclusionStrategy() {&nbsp; &nbsp; &nbsp; &nbsp; public boolean shouldSkipClass(Class<?> clazz) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return (clazz == B.class);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; * Custom field exclusion goes here&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; */&nbsp; &nbsp; &nbsp; &nbsp; public boolean shouldSkipField(FieldAttributes f) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;})&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp; * Use serializeNulls method if you want To serialize null values&nbsp;&nbsp; &nbsp; &nbsp; * By default, Gson does not serialize null values&nbsp; &nbsp; &nbsp; */&nbsp; &nbsp; .serializeNulls()&nbsp; &nbsp; .create();现在我们的通函A a = new A();B b = new B();a.setB(b);b.setA(a);String json = gson.toJson(a);System.out.println(json);看看GsonBuilder类
随时随地看视频慕课网APP

相关分类

Java
我要回答