JSON.NET Error Self referencing loop detected for type


I am trying to convert List into JSON format using the code below

var json = JsonConvert.SerializeObject(ListData);

Where ListData is contains list of ASP.NET User, but when running the above code I am getting this error

JSON.NET Error Self referencing loop detected for type

Note: I tried to serialize POCO class that was automatically generated from Entity Data Model .edmx, and getting the above error.

HOw can I resolve it?


Asked by:- jaiprakash
2
: 227 At:- 8/28/2017 12:06:01 PM
C# serialization json entity-framework






2 Answers
profileImage Answered by:- manish

You are getting this error of self referencing loop because probably there are two classes which are referencing each other using foreign Key and it is quite common error of JSON when you are using .Edmx(without it also you may get issue).

You can resolve this issue by placing this code in Application_Start()

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;

It should resolve your issue, and will not throw error

Or For Single JsonConvert with an overload:

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

Any of the above method will resolve your issue.

2
At:- 8/29/2017 7:47:50 AM
Thanks, I tried the second solution and it is working for me 0
By : jaiprakash - at :- 9/1/2017 7:12:49 AM


profileImage Answered by:- vikas_jk

This may help you

public DBContext() : base("name=DBContext") 
{ 
    Database.SetInitializer(new DBContexttDataInitializer()); 
    this.Configuration.LazyLoadingEnabled = false; 
    this.Configuration.ProxyCreationEnabled = false; 
} 

http://code.msdn.microsoft.com/Loop-Reference-handling-in-caaffaf7

Or  If using ASP.NET Core MVC, add this to the ConfigureServices method of your startup.cs file:

services.AddMvc()
    .AddJsonOptions(
        options => options.SerializerSettings.ReferenceLoopHandling =            
        Newtonsoft.Json.ReferenceLoopHandling.Ignore
    );
1
At:- 9/1/2017 3:08:37 PM





Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use