Thursday, June 13, 2019

Circular reference error while serializing to json

This would fix it (Newtonsoft )

 var jsonResult = JsonConvert.SerializeObject(model, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Serialize });
                var cleanJsonObject = JObject.Parse(jsonResult);
                return cleanJsonObject.ToString();


instead of doing this:

 public JsonResult Genes(string searchterm, string type, string page, string pageSize, string sort)
        {
            //url: /api/search/genes
            try
            {             
                var results = new ProductSearchController().GetGeneCategorySearchResults(searchterm, 25, 1);
                return results;
            }
            catch (Exception ex)
            {
                Log.Error("Error in GetGenes" + ex.Message, ex, this);
                return Json(new
                {
                    result = "There was an error retrieving genes"
                }, JsonRequestBehavior.AllowGet);
            }
        }


Error:

Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.



Enforce the length of string instead of a web config file change

 JsonResult resultJson = Json(new
            {
                result
            }, JsonRequestBehavior.AllowGet);

            resultJson.MaxJsonLength = int.MaxValue;
            return resultJson;


           // return Json(result, JsonRequestBehavior.AllowGet);

No comments:

Post a Comment