Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Solving the problem of Circular References in JSON

0.00/5 (No votes)
12 Mar 2013 1  
The problem of circular reference is a common problem in JSON.

What is the problem of circular references in JSON? 

This problem occurs when you have entities that are interdependent. For example, a Book entity that contains a single or a collection of authors. The Author entity contains also a single or a collection of books. It's as A -> B -> A. Because JSON, like XML, is tree based, it can't deal with that and will throw an exception. 

I faced the problem of circular reference when I started using JSON. I searched the web, there were a lot of solutions for that. But they are not accepted in many cases. Because you will have to change a lot in your Models by adding annotations. Some other solutions will make your application slower, as they suggest to delete the virtual keyword used for lazy loading.

The solution 

What I suggest is to just remove the circular references, but how? You just set a single or collection of the entity Book in the entity Author. But you set the single or collection of the entity Author within the Book to Null. Then you will have (A -> B -> Null), so there are no more circular references!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here