我尝试序列化从实体数据模型.edmx自动生成的POCO类,当我使用
JsonConvert.SerializeObject
我得到了以下错误:
为System.data.entity类型检测到自我引用循环错误。
我怎么解决这个问题?
我尝试序列化从实体数据模型.edmx自动生成的POCO类,当我使用
JsonConvert.SerializeObject
我得到了以下错误:
为System.data.entity类型检测到自我引用循环错误。
我怎么解决这个问题?
当前回答
您也可以将属性应用到属性。 [JsonProperty(ReferenceLoopHandling =…)属性非常适合这一点。
例如:
/// <summary>
/// Represents the exception information of an event
/// </summary>
public class ExceptionInfo
{
// ...code omitted for brevity...
/// <summary>
/// An inner (nested) error.
/// </summary>
[JsonProperty( ReferenceLoopHandling = ReferenceLoopHandling.Ignore, IsReference = true )]
public ExceptionInfo Inner { get; set; }
// ...code omitted for brevity...
}
希望有帮助, 扬
其他回答
非常类似于这里的其他设置,通过使用序列化器设置解决。然而,我的起源,因为我使用FromObject方面的东西,因为我需要一个JObject来工作。
这意味着只需要创建默认序列化器并对其应用设置。简单的修复就变成了这样
var deserializerSettings = new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
};
var serializer = JsonSerializer.CreateDefault(deserializerSettings);
JObject jsonObject = (JObject)JToken.FromObject(mySelfRefernceObject, serializer);
团队:
这适用于ASP。核心网;上面的挑战是如何“设置为忽略”。根据您设置应用程序的方式,这可能相当具有挑战性。以下是对我有效的方法。
这可以放在你的公共void ConfigureServices(IServiceCollection services)部分。
services.AddMvc().AddJsonOptions(opt =>
{
opt.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
在WebApiConfig.cs类中使用:
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
对于. 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/
要在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);
});
}