Self-referencing loop error when attempting serialization

828 views Asked by At

I am attempting to serialize an object (specifically, a distance object in the opensource UnitClassLibrary). Because this library does not have support for serialization apparently, I am willing to modify it for my purposes.

However, I am not sure how to diagnose this problem that is occurring. I am getting the following error when attempting to serialize the object with JSON.net (I have also tried XML serialization using built in tools and get similar errors).

Additional information: Self referencing loop detected for property 'EqualityStrategy' with type 'UnitClassLibrary.DistanceEqualityStrategy'. Path ''.

However, I cannot seem to find any self-referencing loop in the code for a Distance object. How can I go about diagnosing this problem?

I am currently simply trying to serialize like this:

        Distance newDistance = new Distance();
        var json = JsonConvert.SerializeObject(newDistance);

Which is resulting in the error. I can modify the library I am using, but I have not.

1

There are 1 answers

0
KillinIT On

In the past I have seen this problem caused when an object has a nested object in it that references back to the original object.

For example let's say you have an object called Project and it has an attribute that is an object type User. Now inside the User object is a nested object referenced back to the original Project object.

I have been able to ignore the nested looping serialization by using the following JsonSerializerSetting.

In the example below projects is a list of Project objects.

string json = Newtonsoft.Json.JsonConvert.SerializeObject(projects, Newtonsoft.Json.Formatting.Indented,
                new Newtonsoft.Json.JsonSerializerSettings()
                    {
                        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                    }
                );