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?
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.
If you are using .NET Core(3), in starup.cs you will need to add Code as below
services.AddMvc()
.AddJsonOptions(
options => options.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
You will need to install Json.NET from nuget and add the [JsonIgnore] attribute to the virtual property in the class
Something like below:
public string Name { get; set; }
public string Description { get; set; }
public Nullable<int> Order_ID { get; set; }
[JsonIgnore]
public virtual Orders Order { get; set; }
Thanks.
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
);
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly