Search code examples
c#serializationjson.net

JSON.Net Self referencing loop detected


I have a mssql database for my website within 4 tables.

When I use this:

public static string GetAllEventsForJSON()
{
    using (CyberDBDataContext db = new CyberDBDataContext())
    {
        return JsonConvert.SerializeObject((from a in db.Events where a.Active select a).ToList(), new JavaScriptDateTimeConverter());
    }
}

The code results in the following error:

Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property 'CyberUser' with type 'DAL.CyberUser'. Path '[0].EventRegistrations[0].CyberUser.UserLogs[0]'.


Solution

  • I just had the same problem with Parent/Child collections and found that post which has solved my case. I Only wanted to show the List of parent collection items and didn't need any of the child data, therefore i used the following and it worked fine:

    JsonConvert.SerializeObject(ResultGroups, Formatting.None,
                            new JsonSerializerSettings()
                            { 
                                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                            });
    

    JSON.NET Error Self referencing loop detected for type

    it also referes to the Json.NET codeplex page at:

    http://json.codeplex.com/discussions/272371

    Documentation: ReferenceLoopHandling setting