JSON.NET Error Self referencing loop detected for type
c#, json, json.net, serialization
Solution
Use JsonSerializerSettings
- `ReferenceLoopHandling.Error` (default) will error if a reference loop is encountered. This is why you get an exception.
- `ReferenceLoopHandling.Serialize` is useful if objects are nested but not indefinitely.
- `ReferenceLoopHandling.Ignore` will not serialize an object if it is a child object of itself.
Example:
JsonConvert.SerializeObject(YourPOCOHere, Formatting.Indented,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Serialize
});
Should you have to serialize an object that is nested indefinitely you can use PreserveObjectReferences to avoid a StackOverflowException.
Example:
JsonConvert.SerializeObject(YourPOCOHere, Formatting.Indented,
new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects
});
Pick what makes sense for the object you are serializing.
Reference http://james.newtonking.com/json/help/
Problem
I tried to serialize POCO class that was automatically generated from Entity Data Model .edmx and when I used ``` JsonConvert.SerializeObject ``` I got the following error: Error Self referencing loop detected for type System.data.entity occurs. How do I solve this problem?
Related problems
- Asp.Net Web API Error: The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'
- Self referencing loop detected - Getting back data from WebApi to the browser
- How can I do JSON serializer ignore navigation properties?
- Serialize one to many relationships in Json.net