0

I am using gson to serialize my classes. I have some properties that implements an exclusion strategy to avoid circular references. Here is a simple example:

class A{
 B b;
}

class B implements ExclusionStrategy{
 A a
 String str;

 ... implements exclusion strat for class A

}

However, the exclusion strat on A is not called. It still tries to serialize property A in class B. Any ideas on how I can accomplish this? If I just try to serialize class B, it works, so I know the exclusion strat works.

It just doesnt seem to be applied to properties of the containing class. Perhaps there is something I need to add to class A so it knows some of its properties do contain exclusion strategies?

EDIT:

The resulting JSON should look something like:

{
    B
    {
        'str':'some str'
    }
}
user489041
  • 27,916
  • 55
  • 135
  • 204
  • How have you implemented the exclusion? And how have you registered it? What do you want your resulting JSON to look like? Are you currently getting a stack overflow from the circular reference? – Sotirios Delimanolis Feb 17 '15 at 20:33
  • Yes, I am getting a stack overflow. I have implemented the exlcusion strategy in class B to avoid serializing class A. I am sure thats where the stackoverflow is coming from. Howver, I only ever serialize class A. Is there a way to register the exclusion classes if the are contained in class B even though I am serializing class A? – user489041 Feb 17 '15 at 20:34
  • Are you using `GsonBuilder#setExclusionStrategies`? – Sotirios Delimanolis Feb 17 '15 at 20:37
  • Oh, do you want to skip `B.a` **only** if you're already serializing `A`? And vice versa? In other words, if you only serialize a `B`, you want the `A.b` to be skipped, and if you serialize an `A`, you want `B.a` to be skipped? – Sotirios Delimanolis Feb 17 '15 at 20:39
  • Yes, something along those lines. It just needs to be serialized once to avoid circular references – user489041 Feb 17 '15 at 20:41
  • I don't think Gson is well suited for this. [Jackson](http://stackoverflow.com/a/3359884/438154) seems to have a better solution. – Sotirios Delimanolis Feb 17 '15 at 20:46

0 Answers0