How to solve self referencing loop issue when using Newtonsoft.Json?

I recently published a post that explains how to process JSON using C# and Newtonsoft.Json. Using Newtonsoft.Json framework is the best way to serialize and deserialize any .NET object. In this post, I’ll tell you how to solve self referencing loop issue when using Newtonsoft.Json framework.

Say suppose when you are trying to serialize a .NET object using JsonConvert.SerializeObject() that references itself in some way, when you run your application an unhandled exception of type ‘Newtonsoft.Json.JsonSerializationException’ will be encountered in Newtonsoft.Json.dll. You will also find some additional information such as “Additional information: Self referencing loop detected with type ‘some class name’.Path ‘some property name'”.

Let us understand the cause of this using an example. I’ll be using an Author class that I used initially in my previous post. The class definition looks like this:

To see the result quickly, I’m using a console application of whichProgram class looks like below:

Let us now look at the implementation of ShowDemo method of ProcessByValueReferenceDemo class below:

Let us now understand the code above:

  • Line no. 5-7 defines 3 different Author objects.
  • Line no. 9 then defines the FavouriteAuthors property of object named sid. Notice that the same object has been added to this property.
  • When JsonConvert.SerializeObject(sid) is executed on line no. 13, an exception is thrown that says “An unhandled exception of type ‘Newtonsoft.Json.JsonSerializationException’ occurred in Newtonsoft.Json.dll”. The main reason behind this is JsonConvert by default process the object by value and not by reference. You can see in the code that I’ve added this statement in a try catch block so that the application doesn’t stop due to this exception.
  • Line no. 22-26 uses an overload of SerializeObject and passes JsonSerializerSettings object that instructs the underlying JsonSerializer to process this object by reference by using PreserveReferencesHandling = PreserveReferencesHandling.Objects. By specifying this setting, the object is now serialized properly. Also, the formatting is indented to format the result. The result now looks like this:

Let’s look at the magic done to the result output just by using PreserveReferencesHandling.Objects. You will notice that each JSON object now has a new member named $id at line no. 2, 14 and 27. And this identifier is then used at places where ever a reference is needed such as on line no. 11, 24, 37, 40.

This basically creates an object only once and reference it wherever required. Also, the good thing about this is as such the reference is preserved within the JSON result, when you will deserialize this JSON back to a .NET object of type Author then it will again create the source object(s) only once and will create the other similar object(s) that just references the source object(s).

PreserveReferencesHandling is an enum that allows the same concept to apply on Object, Arrays, All (Arrays and Objects). The default is None.

I hope this is useful to solve self referencing loop issue when using Newtonsoft.Json. I’ll be writing more posts about this popular high-performance JSON framework soon. If you would like to get updates, please subscribe to my blog.

Siddharth Pandey

Siddharth Pandey is a Software Engineer with thorough hands-on commercial experience & exposure to building enterprise applications using Agile methodologies. Siddharth specializes in building, managing on-premise, cloud based real-time standard, single page web applications (SPAs). He has successfully delivered applications in health-care, finance, insurance, e-commerce sectors for major brands in the UK. Other than programming, he also has experience of managing teams, trainer, actively contributing to the IT community by sharing his knowledge using Stack Overflow, personal website & video tutorials.

You may also like...

Advertisment ad adsense adlogger