JSON.Net Self referencing loop detected

前端 未结 11 856
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 04:18

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

When I use this:

public static string GetAllEventsForJSON()
{
    using (CyberDBDataContext d         


        
11条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 04:47

    The fix is to ignore loop references and not to serialize them. This behaviour is specified in JsonSerializerSettings.

    Single JsonConvert with an overload:

    JsonConvert.SerializeObject((from a in db.Events where a.Active select a).ToList(), Formatting.Indented,
        new JsonSerializerSettings() {
            ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
        }
    );
    

    If you'd like to make this the default behaviour, add a Global Setting with code in Application_Start() in Global.asax.cs:

    JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
         Formatting = Newtonsoft.Json.Formatting.Indented,
         ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    };
    

    Reference: https://github.com/JamesNK/Newtonsoft.Json/issues/78

提交回复
热议问题