4

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.

Jake
  • 3,411
  • 4
  • 21
  • 37
  • Please post your modified object code. – Der Kommissar May 18 '15 at 19:00
  • tried to clarify EBrown. – Jake May 18 '15 at 19:02
  • 1
    The issue is **probably** because of the `public DistanceEqualityStrategy EqualityStrategy` object, which itself is a `delegate` of two `Distance` objects. I would be that's where the issue comes in. You would need to specify to the JSON Serializer, and XML Serializer, not to serialize that object. (`[ScriptIgnore]`, `[XmlIgnore]`) – Der Kommissar May 18 '15 at 19:05
  • I'll try that. I'm not able to reference System.Web currently as UCL is PCL, but I can make a non-PCL version as that's not important. – Jake May 18 '15 at 19:23
  • 2
    Since you're using json.net, the attribute would be [`[JsonIgnore]`](http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonIgnoreAttribute.htm). – dbc May 18 '15 at 19:56
  • For now I'm using [JsonIgnore]. Feel free to make an answer and I can accept it. – Jake May 19 '15 at 13:38

1 Answers1

2

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
                    }
                );
KillinIT
  • 21
  • 2