我尝试序列化从实体数据模型.edmx自动生成的POCO类,当我使用
JsonConvert.SerializeObject
我得到了以下错误:
为System.data.entity类型检测到自我引用循环错误。
我怎么解决这个问题?
我尝试序列化从实体数据模型.edmx自动生成的POCO类,当我使用
JsonConvert.SerializeObject
我得到了以下错误:
为System.data.entity类型检测到自我引用循环错误。
我怎么解决这个问题?
当前回答
我有这个例外,我的工作解决方案很简单,
通过添加JsonIgnore属性来忽略引用属性:
[JsonIgnore]
public MyClass currentClass { get; set; }
反序列化时重置属性:
Source = JsonConvert.DeserializeObject<MyObject>(JsonTxt);
foreach (var item in Source)
{
Source.MyClass = item;
}
使用Newtonsoft.Json;
其他回答
我们可以将这两行添加到DbContext类构造函数中以禁用Self引用循环,例如
public TestContext()
: base("name=TestContext")
{
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
}
我喜欢从Application_Start()做它的解决方案,在这里的答案
显然,我不能在JavaScript中使用我的函数中的配置访问json对象,因为在DalSoft的答案中返回的对象在对象的(键,val)上都有“\n \r”。
不管怎样,只要能工作就好(因为不同的方法在不同的场景下工作,这取决于所提出的意见和问题),尽管最好采用一种标准的方法,并提供一些良好的文档支持该方法。
修复方法是忽略循环引用,不序列化它们。此行为在JsonSerializerSettings中指定。
带重载的单个JsonConvert:
JsonConvert.SerializeObject(YourObject, 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
对于. net Core 3.0,更新Startup.cs类,如下所示。
public void ConfigureServices(IServiceCollection services)
{
...
services.AddControllers()
.AddNewtonsoftJson(
options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
...
}
参见:https://devblogs.microsoft.com/aspnet/asp-net-core-updates-in-net-core-3-0-preview-5/
在。net Core 1.0中,你可以在Startup.cs文件中设置全局设置:
using System.Buffers;
using Microsoft.AspNetCore.Mvc.Formatters;
using Newtonsoft.Json;
// beginning of Startup class
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.OutputFormatters.Clear();
options.OutputFormatters.Add(new JsonOutputFormatter(new JsonSerializerSettings(){
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
}, ArrayPool<char>.Shared));
});
}