A circular reference was detected while serializing an object of type

Hi All,

I am using MVC4 and Entity Framework  in my application .

I am serializing my model using JsonSerialize

the code looks like this.

        public static string Serialize(object value)
        {
            
            string formattedItem = JsonConvert.SerializeObject(value, JsonSerializationSettings.Settings);           
           
            formattedItem = formattedItem.Replace(""$type": "", ""type": "");

            return formattedItem;
        }

So I tried using 

 ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore  

   & also tried this 
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,

PreserveReferencesHandling = PreserveReferencesHandling.Objects

When I Use ReferenceLoopHandling, PreserveReferencesHandling  .. there is no circular reference error , but the Json returned is not correct .

How should I solve this problem , Could anyone please suggest .

Thanks

Hi , that link shows the simple structure , but I have a very complex structure of Parent and Child relation ,

Please suggest

Thanks

Hi gowrifor,

For the one-to-many or many-to-many relations, we can’t serialize it directly.

The easy way is that you could use ViewModel or anonymous (select new{}) type, then serialize it.

You also could refer to this article to try to do by yourself:

# Refactoring with LINQ

https://prashantbrall.wordpress.com/tag/entity-framework-and-poco/

There are some links that may benefit you:

# Serializing Entity Framework Objects into JSON Using ASP.Net MVC

http://mytechworld.azurewebsites.net/2010/02/serializing-entity-framework-objects-into-json-using-asp-net-mvc/

# JavaScriptSerializer circular reference when using ScriptIgnore

http://stackoverflow.com/questions/14569207/javascriptserializer-circular-reference-when-using-scriptignore

Best Regards

Starain Chen

Leave a Reply