JSON Circular reference problem

Source: Internet
Author: User

154down Votefavorite27

I am trying to does a simple JSON return I am has issues I have the following below.

public JsonResult GetEventData(){    var data = Event.Find(x => x.ID != 0);    return Json(data);}

I get a HTTP exception as shown in the title of this question. I also tried

var data = Event.All().ToList()

That gave the same problem.

Is this a bug or my implementation?

It seems that there was circular references in your object hierarchy which was not supported by the JSON serializer. Need all the columns? You could pick up only the properties of you need in the view:

return Json(new {      PropertyINeed1 = data.PropertyINeed1,    PropertyINeed2 = data.PropertyINeed2});

This would make your the JSON object lighter and easier to understand. If you have many properties, AutoMapper could is used to automatically map between DTO objects and View objects.

I had the same problem and solved byusing Newtonsoft.Json;

var list = JsonConvert.SerializeObject(model,    Formatting.None,    new JsonSerializerSettings() {        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore});return Content(list, "application/json");




50down vote

This actually happens because the complex objects is what makes the resulting JSON object fails. And it fails because when the object is mapped it maps the children, which maps their parents, making a circular reference to occur. Json would take infinite time-to-serialize it prevents the problem with the exception.

The Entity Framework mapping also produces the same behavior, and the solution are to discard all unwanted properties.

Just expliciting The final answer, the whole code would be:

public JsonResult getJson(){    DataContext db = new DataContext ();    return this.Json(           new {                Result = (from obj in db.Things select new {Id = obj.Id, Name = obj.Name})               }           , JsonRequestBehavior.AllowGet           );}

It could also is the following in case you don ' t want the objects inside a property Result :

public JsonResult getJson(){    DataContext db = new DataContext ();    return this.Json(           (from obj in db.Things select new {Id = obj.Id, Name = obj.Name})           , JsonRequestBehavior.AllowGet           );}


To sum things up, there is 3 solutions to this:

    Private DBEntities db = new DBEntities ()//dbcontext//solution 1:turn off proxycreation for the DbContext and res Tore it in the end public ActionResult Index () {bool proxycreation = db.        configuration.proxycreationenabled; try {//set proxycreation to false db.            configuration.proxycreationenabled = false; var data = db.            Products.tolist ();        return Json (data, jsonrequestbehavior.allowget);            } catch (Exception ex) {response.statuscode = (int) httpstatuscode.badrequest; Return Json (ex.        Message); The finally {//restore proxycreation to their original state db.        configuration.proxycreationenabled = proxycreation;     }}//solution 2:using JsonConvert by Setting referenceloophandling to ignore on the serializer settings.    Using using Newtonsoft.json; Public ActionResult Index () {try {var data = db.            Products.tolist ();            Jsonserializersettings JSS = new Jsonserializersettings {referenceloophandling = Referenceloophandling.ignore};            var result = Jsonconvert.serializeobject (data, formatting.indented, JSS);        return Json (result, jsonrequestbehavior.allowget);            } catch (Exception ex) {response.statuscode = (int) httpstatuscode.badrequest; Return Json (ex.        Message);    }}//solution 3:return a new dynamic object which includes only the needed properties. Public ActionResult Index () {try {var data = db.                                                    Products.select (p = new {                                                    product_id = p.product_id, product_name = P.product_name,                                                Product_price = P.product_price }). ToLIST ();        return Json (data, jsonrequestbehavior.allowget);            } catch (Exception ex) {response.statuscode = (int) httpstatuscode.badrequest; Return Json (ex.        Message); }    }





TS because of the new DbContext T4 template that's used for generating the entityframework entities. In order to being able to perform the change tracking, this templates uses the Proxy pattern, by wrapping your nice pocos wit H them. This and causes the issues when serializing with the JavaScriptSerializer.

So and the 2 solutions are:

    1. Either just serialize and return the properties you need on the client
    2. You could switch off the automatic generation of proxies by setting it on the context ' s configuration

      Context. configuration.proxycreationenabled = false;

Very well explained in the below article.

http://juristr.com/blog/2011/08/javascriptserializer-circular-reference/

JSON Circular reference problem

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.