C# 检测到 JSON.Net 自引用循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13510204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON.Net Self referencing loop detected
提问by Kovu
I have a mssql database for my website within 4 tables.
我的网站有一个 mssql 数据库,包含 4 个表。
When I use this:
当我使用这个时:
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());
}
}
The code results in the following error:
该代码导致以下错误:
Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property 'CyberUser' with type 'DAL.CyberUser'. Path '[0].EventRegistrations[0].CyberUser.UserLogs[0]'.
Newtonsoft.Json.JsonSerializationException:检测到类型为“DAL.CyberUser”的属性“CyberUser”的自引用循环。路径“[0].EventRegistrations[0].CyberUser.UserLogs[0]”。
采纳答案by Muhammad Omar ElShourbagy
I just had the same problem with Parent/Child collections and found that post which has solved my case. I Only wanted to show the List of parent collection items and didn't need any of the child data, therefore i used the following and it worked fine:
我刚刚在父/子集合中遇到了同样的问题,并找到了解决我的案例的帖子。我只想显示父集合项列表,不需要任何子数据,因此我使用了以下内容并且效果很好:
JsonConvert.SerializeObject(ResultGroups, Formatting.None,
new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
JSON.NET Error Self referencing loop detected for type
it also referes to the Json.NET codeplex page at:
它还引用了 Json.NET codeplex 页面:
http://json.codeplex.com/discussions/272371
http://json.codeplex.com/discussions/272371
Documentation: ReferenceLoopHandling setting
回答by smockle
The fix is to ignore loop references and not to serialize them. This behaviour is specified in JsonSerializerSettings.
解决方法是忽略循环引用而不是序列化它们。此行为在 中指定JsonSerializerSettings。
Single JsonConvertwith an overload:
SingleJsonConvert过载:
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 Settingwith code in Application_Start()in Global.asax.cs:
如果您想将此设置为默认行为,请在 Global.asax.cs 中添加带有代码的
全局设置Application_Start():
JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
Formatting = Newtonsoft.Json.Formatting.Indented,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};
Reference: https://github.com/JamesNK/Newtonsoft.Json/issues/78
回答by ddagsan
This may help you.
这可能对你有帮助。
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
http://code.msdn.microsoft.com/Loop-Reference-handling-in-caaffaf7
回答by andreisrob
If using ASP.NET Core MVC, add this to the ConfigureServices method of your startup.cs file:
如果使用 ASP.NET Core MVC,请将其添加到 startup.cs 文件的 ConfigureServices 方法:
services.AddMvc()
.AddJsonOptions(
options => options.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
回答by Cyrus
You must set Preserving Object References:
您必须设置保留对象引用:
var jsonSerializerSettings = new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects
};
Then call your query var q = (from a in db.Events where a.Active select a).ToList();like
然后打电话给你的查询var q = (from a in db.Events where a.Active select a).ToList();像
string jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(q, jsonSerializerSettings);
string jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(q, jsonSerializerSettings);
See: https://www.newtonsoft.com/json/help/html/PreserveObjectReferences.htm
请参阅:https: //www.newtonsoft.com/json/help/html/PreserveObjectReferences.htm
回答by user3824027
JsonConvert.SerializeObject(ObjectName, new JsonSerializerSettings(){
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
Formatting = Formatting.Indented
});
JsonConvert.SerializeObject(ObjectName, new JsonSerializerSettings(){
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
Formatting = Formatting.Indented
});
回答by Samet Sunman
Add "[JsonIgnore]" to your model class
将“[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; }
}
回答by krishnan2784
I am using Dot.Net Core 3.1 and did an search for
我正在使用 Dot.Net Core 3.1 并搜索了
"Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property "
“Newtonsoft.Json.JsonSerializationException:检测到属性的自引用循环”
I am adding this to this question, as it will be an easy reference. You should use the following in the Startup.cs file:
我将此添加到这个问题中,因为它将是一个简单的参考。您应该在 Startup.cs 文件中使用以下内容:
services.AddControllers()
.AddNewtonsoftJson(options =>
{
// Use the default property (Pascal) casing
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
回答by Angélica Tovar
Sometimes you have loops becouse your type class have references to other classes and that classes have references to your type class, thus you have to select the parameters that you need exactly in the json string, like this code.
有时你有循环,因为你的类型类引用了其他类,而这些类引用了你的类型类,因此你必须在 json 字符串中选择你需要的参数,就像这段代码。
List<ROficina> oficinas = new List<ROficina>();
oficinas = /*list content*/;
var x = JsonConvert.SerializeObject(oficinas.Select(o => new
{
o.IdOficina,
o.Nombre
}));

