spiderplant0
spiderplant0

Reputation: 3952

"Self referencing loop detected" in Newtonsoft.Json

For this code...

private void Label1_MouseUp(object sender, RoutedEventArgs e)
{
    Newtonsoft.Json.Linq.JObject.FromObject(e).ToString();
}

I get this error...

Self referencing loop detected with type 'System.Windows.Documents.Run'. Path 'MouseDevice.Target.Inlines[0].SiblingInlines'.

There are plenty of other similar question, but I cant figure out how to implement the solutions in my case (I am learning C#). E.g. add ReferenceLoopHandling = ReferenceLoopHandling.Ignore But cant figure out where to put this.

(By the way, I'm trying to find a simple general-purpose way of printing out debug info.)

Upvotes: 3

Views: 5388

Answers (2)

Captain Whippet
Captain Whippet

Reputation: 2223

In your question you said that you can't figure out where to put the ReferenceLoopHandling = ReferenceLoopHandling.Ignore. You can put this in your call to `FromObject' as follows:

JObject.FromObject(e, new JsonSerializer() {
    ReferenceLoopHandling = ReferenceLoopHandling.Ignore });

Here's a link to the JObject.FromObject documentation: http://james.newtonking.com/json/help/index.html?topic=html/CreatingLINQtoJSON.htm

Upvotes: 5

Orel Eraki
Orel Eraki

Reputation: 12196

Yes, This is very common problem, and the error message say it all.

As you guess what you got is reference that already been serilize thus resulting in infinite action to recursion to serilize that object. If you will mark it as Ignore ReferenceLoopHandling the serilize will keep on working and will produce you a StackoverflowException.

Instead you have few solutions, here are 2 of them:

  • You can identify which of the properties is causing that loop, and set it on null if not needed.
  • You can create another class specific for prepare the serilize object, populate it, and than serilize it.

Upvotes: 0

Related Questions