JSON.Net检测到自回参考循环

我在我的网站有4个表格的mssql数据库。

当我使用这个:

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()); } } 

该代码导致以下错误:

Newtonsoft.Json.JsonSerializationException:检测到types为“DAL.Cyber​​User”的属性“Cyber​​User”的自回参考循环。 path'[0] .EventRegistrations [0] .Cyber​​User.UserLogs [0]'。

我只是有与父母/子集合相同的问题,并发现解决我的情况的职位。 我只想显示父级收集项目的列表,并不需要任何的孩子数据,因此我用了以下,它工作正常:

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

JSON.NET错误检测到types的自我引用循环

它也参考Json.NET codeplex页面:

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

文档: ReferenceLoopHandling设置

修复是忽略循环引用,而不是序列化它们。 此行为在JsonSerializerSettings指定。

带过载的单个JsonConvert

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

如果您希望将其设置为默认行为,请在Global.asax.cs中的Application_Start()中添加代码的全局设置

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

参考: https : //github.com/JamesNK/Newtonsoft.Json/issues/78

这可能会帮助你。

 public MyContext() : base("name=MyContext") { Database.SetInitializer(new MyContextDataInitializer()); this.Configuration.LazyLoadingEnabled = false; this.Configuration.ProxyCreationEnabled = false; } 

http://code.msdn.microsoft.com/Loop-Reference-handling-in-caaffaf7

如果使用ASP.NET Core MVC,请将其添加到startup.cs文件的ConfigureServices方法中:

 services.AddMvc() .AddJsonOptions( options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore ); 

您必须设置保留对象引用:

 var jsonSerializerSettings = new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects }; 

http://www.newtonsoft.com/json/help/html/PreserveObjectReferences.htm