Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve circular reference in json serializer caused by hibernate bidirectional mapping?

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?

like image 736
WSK Avatar asked Jul 27 '10 03:07

WSK


1 Answers

I rely on Google JSON To handle this kind of issue by using The feature

Excluding Fields From Serialization and Deserialization

Suppose a bi-directional relationship between A and B class as follows

public class A implements Serializable {      private B b;  } 

And B

public class B implements Serializable {      private A a;  } 

Now use GsonBuilder To get a custom Gson object as follows (Notice setExclusionStrategies method)

Gson gson = new GsonBuilder()     .setExclusionStrategies(new ExclusionStrategy() {          public boolean shouldSkipClass(Class<?> clazz) {             return (clazz == B.class);         }          /**           * Custom field exclusion goes here           */         public boolean shouldSkipField(FieldAttributes f) {             return false;         }       })     /**       * Use serializeNulls method if you want To serialize null values        * By default, Gson does not serialize null values       */     .serializeNulls()     .create(); 

Now our circular reference

A a = new A(); B b = new B();  a.setB(b); b.setA(a);  String json = gson.toJson(a); System.out.println(json); 

Take a look at GsonBuilder class

like image 108
Arthur Ronald Avatar answered Sep 23 '22 10:09

Arthur Ronald