PanosPlat
PanosPlat

Reputation: 958

MVC serialize json using Json.NET

I have this code inside a Controller

[HttpPost]
public ActionResult Index([DataSourceRequest]DataSourceRequest request)
{
    var tickets = db.Tickets.Include(t => t.AreaOfBusiness).Include(t => t.Assignee).Include(t => t.Severity).Include(t => t.TicketStatu);
    return this.Json(tickets.ToDataSourceResult(request));
}

but I get

A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.Ticket_2B104FE45830306408DA130C08090F61ADA6B8A0106592FECE85087B94B

when launching KendoGrid.

I read that NewtonSoft Json.Net can handle Circular Reference. I cannot understand how to use it.

Can you help me modify the code in order to use the Json.Net?

Thanx in advance!

Upvotes: 0

Views: 1485

Answers (2)

L.Trabacchin
L.Trabacchin

Reputation: 1620

Or... you can enable json.net feature to serialize handling circular references for objects

in your global.asax.cs

System.Net.Http.Formatting.JsonMediaTypeFormatter jsonMediaTypeFormatter = GlobalConfiguration.Configuration.Formatters.OfType<System.Net.Http.Formatting.JsonMediaTypeFormatter>().FirstOrDefault();
jsonMediaTypeFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
jsonMediaTypeFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;

remember to disable lazy loading or it will download the whole database, use include on dbsets to keep the relationships you want and to parse the json that will behave like a dictionary now, example here: https://gist.github.com/keesey/7995398

Upvotes: 1

andres descalzo
andres descalzo

Reputation: 14967

ToDataSourceResult return the object DataSourceResult.

Kendo Documentation

A circular reference was detected while serializing an object of type

The reason for this error is that the JavaScriptSerializer class used by the Json method cannot serialize object graphs which contain circular references (refer to each other). The best solution is to use View Model objects and avoid the serializing the properties which create the circular reference. Check the "How do I avoid circular reference exceptions" FAQ section for further information.

see documentation

"How do I avoid circular reference exceptions?":

The JavaScriptSerializer class will throw an exception if the serialized object contains circular references. To avoid that use a View Model and exclude the properties which create the circular references

see example

More data

Upvotes: 1

Related Questions