我尝试序列化从实体数据模型.edmx自动生成的POCO类,当我使用
JsonConvert.SerializeObject
我得到了以下错误:
为System.data.entity类型检测到自我引用循环错误。
我怎么解决这个问题?
我尝试序列化从实体数据模型.edmx自动生成的POCO类,当我使用
JsonConvert.SerializeObject
我得到了以下错误:
为System.data.entity类型检测到自我引用循环错误。
我怎么解决这个问题?
当前回答
修复方法是忽略循环引用,不序列化它们。此行为在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
其他回答
最简单的方法是安装Json。网 从nuget中添加[JsonIgnore]属性到类的虚拟属性中,例如:
public string Name { get; set; }
public string Description { get; set; }
public Nullable<int> Project_ID { get; set; }
[JsonIgnore]
public virtual Project Project { get; set; }
尽管这些天,我创建了一个只包含我想要传递的属性的模型,所以它更轻,不包括不需要的集合,并且当我重新构建生成的文件时,我不会丢失我的更改……
使用JsonSerializerSettings
ReferenceLoopHandling。如果遇到引用循环,Error(默认)将出错。这就是为什么会出现异常。 ReferenceLoopHandling。如果对象嵌套但不是无限的,序列化是有用的。 ReferenceLoopHandling。如果对象是自身的子对象,Ignore将不会序列化该对象。
例子:
JsonConvert.SerializeObject(YourPOCOHere, Formatting.Indented,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Serialize
});
如果你必须序列化一个无限嵌套的对象,你可以使用PreserveObjectReferences来避免StackOverflowException。
例子:
JsonConvert.SerializeObject(YourPOCOHere, Formatting.Indented,
new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects
});
选择对要序列化的对象有意义的内容。
参考http://james.newtonking.com/json/help/
要在MVC 6中忽略循环引用并且不全局序列化它们,请在startup.cs中使用以下命令:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().Configure<MvcOptions>(options =>
{
options.OutputFormatters.RemoveTypesOf<JsonOutputFormatter>();
var jsonOutputFormatter = new JsonOutputFormatter();
jsonOutputFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
options.OutputFormatters.Insert(0, jsonOutputFormatter);
});
}
我有这个例外,我的工作解决方案很简单,
通过添加JsonIgnore属性来忽略引用属性:
[JsonIgnore]
public MyClass currentClass { get; set; }
反序列化时重置属性:
Source = JsonConvert.DeserializeObject<MyObject>(JsonTxt);
foreach (var item in Source)
{
Source.MyClass = item;
}
使用Newtonsoft.Json;
我的问题解决了自定义配置JsonSerializerSettings:
services.AddMvc(
// ...
).AddJsonOptions(opt =>
{
opt.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Serialize;
opt.SerializerSettings.PreserveReferencesHandling =
Newtonsoft.Json.PreserveReferencesHandling.Objects;
});