C # recursion restriction when returning JSON

I recently ran into an annoying problem. I am going to simplify my database here, but the principle is the same. I have a class "User". In this class, I have a property that is a list of objects that the user owns. I also have this class "object". Since each "object" has an owner, it has a property of type "User", which refers to its owner. Now, what I'm trying to do is basically

return Json(myUser,JsonRequestBehavior.AllowGet); 

When I load the page, it takes 30 seconds, and then I get the error "RecursionLimit above".

I assume that this is due to the fact that objects are related to each other. Now my question is: how can I say "Json" that it should not go deeper than level 1 objects to avoid this?

+8
c # asp.net-mvc-3
source share
4 answers

myUser is probably the type created by EntityFramework.

When you return Json, the framework will prepare each property essentially, invoking an SQL command to lazily load all the data.

Instead, you should prepare the ViewModel class with specific properties that are not bound to EntityFramework, and prepare this object as deep as you want.

+7
source share

This can happen when your object has some properties. eg.

 public object Employee() { string ID {get; set;} string Name {get; set;} int Age {get; set;} Employee Boss{get; set;} //<-- here } var employee = new Employee(); return Json(employee,JsonRequestBehavior.AllowGet); //The Boss property will cause "RecursionLimit exceeded". 

To avoid this. you can do something like this:

 var employee = new Employee(); var prepareForJson = new { ID = employee.ID, Name = employee.Name, Age = employee.Age, Boss = employee.Boss.ID }; return Json(prepareForJson , JsonRequestBehavior.AllowGet); 
+6
source share

You can adjust the recursion depth via web.config

http://msdn.microsoft.com/en-us/library/bb763183.aspx

but you probably just want to sort your model so as not to have recursion in the first place. Think about how much data is needed in your current situation and return only that.

+3
source share

I think that Edison Chuang is the answer for the vast majority of cases (mapping data models to some service models that don't have navigation features that will certainly cause loops during serialization).

However, since most service models will share many of the properties of data models (EF models), AutoMapper can use it, greatly simplifying the code, especially for objects with many properties. For example:.

 // set up map cfg.CreateMap<Employee, EmployeeSm>(); // use the map var sm = Mapper.Map<EmployeeSm>(employee); // this can be also set up during mapping configuration phase sm.Boss = employee.Boss.ID; 

In those rare cases where the serialization depth goes beyond 100 by default, you can either increase this limit or use Json.NET to serialize objects.

0
source share

All Articles