检测到JSON.Net自引用循环

Kov*_*ovu 94 c# serialization 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());
    }
}
Run Code Online (Sandbox Code Playgroud)

该代码导致以下错误:

Newtonsoft.Json.JsonSerializationException:为类型为"DAL.Cyber​​User"的属性"Cyber​​User"检测到自引用循环.路径'[0] .EventRegistrations [0] .Cyber​​User.UserLogs [0]'.

Muh*_*agy 176

我刚与父/子集合有同样的问题,发现那个帖子解决了我的情况.我只想显示父集合项列表,并且不需要任何子数据,因此我使用了以下内容并且工作正常:

JsonConvert.SerializeObject(ResultGroups, Formatting.None,
                        new JsonSerializerSettings()
                        { 
                            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                        });
Run Code Online (Sandbox Code Playgroud)

JSON.NET错误检测到类型的自引用循环

它还引用了Json.NET codeplex页面:

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

文档:ReferenceLoopHandling设置

  • 根据具体情况,你也可以使用`PreserveReferencesHandling = PreserveReferencesHandling.Objects;`,如下所述:[solve-self-referencing-loop-issue-when-using-newtonsoft-json](http://www.siddharthpandey.net/解决自参照 - 环 - 问题 - 当 - 使用 - newtonsoft-JSON /) (2认同)
  • 即使使用“忽略”设置 newtonsoft 似乎也会部分序列化自引用。在我的代码中,序列化数据似乎比实际数据(序列化时)大 80 倍。 (2认同)

smo*_*kle 39

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

单人JsonConvert过载:

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

如果您想将此作为默认行为,请在Global.asax.cs中添加包含代码的 全局设置Application_Start():

JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
     Formatting = Newtonsoft.Json.Formatting.Indented,
     ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};
Run Code Online (Sandbox Code Playgroud)

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

  • 对此进行序列化需要很长时间 (3认同)

and*_*rob 33

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

services.AddMvc()
    .AddJsonOptions(
        options => options.SerializerSettings.ReferenceLoopHandling =            
        Newtonsoft.Json.ReferenceLoopHandling.Ignore
    );
Run Code Online (Sandbox Code Playgroud)

  • 我已经确认此解决方案也适用于WebAPI EntityFramework Core 2.0 (2认同)

dda*_*san 13

这可能对你有所帮助.

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

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

  • 如果您还使用异步方法,这是接近它的最佳方法.这可能是一个真正的痛苦,但它解决了许多你本来会遇到的问题(包括这个问题),并且因为你只是在询问你将使用什么,所以也可以提高性能. (4认同)

小智 7

对于 asp.net core 3.1.3 这对我有用

services.AddControllers().AddNewtonsoftJson(opt=>{
            opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        });
Run Code Online (Sandbox Code Playgroud)


Sam*_*man 6

将“[JsonIgnore]”添加到您的模型类中

{
  public Customer()
  {
    Orders = new Collection<Order>();
  }

public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }

[JsonIgnore]
public ICollection<Order> Orders { get; set; }
}
Run Code Online (Sandbox Code Playgroud)


小智 6

我正在使用 Dot.Net Core 3.1 并搜索了

“Newtonsoft.Json.JsonSerializationException:检测到属性的自引用循环”

我将此添加到这个问题中,因为它将是一个简单的参考。您应该在 Startup.cs 文件中使用以下内容:

 services.AddControllers()
                .AddNewtonsoftJson(options =>
                {
                    // Use the default property (Pascal) casing
                    options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                });
Run Code Online (Sandbox Code Playgroud)


Cyr*_*rus 5

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

var jsonSerializerSettings = new JsonSerializerSettings
{
    PreserveReferencesHandling = PreserveReferencesHandling.Objects
};
Run Code Online (Sandbox Code Playgroud)

然后var q = (from a in db.Events where a.Active select a).ToList();像这样调用您的查询

string jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(q, jsonSerializerSettings);

请参阅:https//www.newtonsoft.com/json/help/html/PreserveObjectReferences.htm