卢声远 Shengyuan Lu
卢声远 Shengyuan Lu

Reputation: 32004

StackOverflowError occurs when serialize nested objects to JSON string

Here is nested object in Groovy:

class A{
    B b
}

class B{
    A a
}

A a = new A()
B b = new B()
a.b = b
b.a = a

Then StackOverflowError occurs when new JsonBuilder(a).toString() is called.

Do we have any configuration for the JsonBuilder? Or it's impossible to do that. By the way, the nested objects is from Hibernate.

Thanks!

Upvotes: 1

Views: 402

Answers (3)

Xiezi
Xiezi

Reputation: 2989

Based on the description of the question, it seems like you are dealing with data like this:

DB(Data) --> YourApp(POJO) --> External(JSON)

But, from the design perspective, I think this doesn't seem the right thing to do to expose your internal DB data model for external usage. It may be better for many reasons to use new models for serialization:

  1. Security. As I mentioned above.
  2. Extensibility. Even the model you are using are same for now, they may be changed and different in the future.
  3. Simpleness.

Upvotes: 1

Santosh
Santosh

Reputation: 17913

With the given scenario and the error you are getting, it can be concluded that JsonBuilder does nto handle cyclic references (which is there in your object structure). I am not sure which library you are using but you can crosscheck that with the source code if available.

As an alternative, I would suggest to explore other libraries which handle the cyclic reference. Check Jackson which is known to handle cyclic references.

Upvotes: 0

Lucas
Lucas

Reputation: 3281

If you're doing bidirectional relationship in Hibernate you can make objects hold reference to another (such as id) instead of the actual object which causes this problem.

Upvotes: 0

Related Questions