我尝试序列化从实体数据模型.edmx自动生成的POCO类,当我使用
JsonConvert.SerializeObject
我得到了以下错误:
为System.data.entity类型检测到自我引用循环错误。
我怎么解决这个问题?
我尝试序列化从实体数据模型.edmx自动生成的POCO类,当我使用
JsonConvert.SerializeObject
我得到了以下错误:
为System.data.entity类型检测到自我引用循环错误。
我怎么解决这个问题?
当前回答
当你有循环问题时,序列化使用NEWTONSOFTJSON,在我的情况下,我不需要修改全局。野蔷薇或野蔷薇。我只是使用JsonSerializesSettings忽略循环处理。
JsonSerializerSettings jss = new JsonSerializerSettings();
jss.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
var lst = db.shCards.Where(m => m.CardID == id).ToList();
string json = JsonConvert.SerializeObject(lst, jss);
其他回答
您也可以将属性应用到属性。 [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...
}
希望有帮助, 扬
当你有循环问题时,序列化使用NEWTONSOFTJSON,在我的情况下,我不需要修改全局。野蔷薇或野蔷薇。我只是使用JsonSerializesSettings忽略循环处理。
JsonSerializerSettings jss = new JsonSerializerSettings();
jss.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
var lst = db.shCards.Where(m => m.CardID == id).ToList();
string json = JsonConvert.SerializeObject(lst, jss);
非常类似于这里的其他设置,通过使用序列化器设置解决。然而,我的起源,因为我使用FromObject方面的东西,因为我需要一个JObject来工作。
这意味着只需要创建默认序列化器并对其应用设置。简单的修复就变成了这样
var deserializerSettings = new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
};
var serializer = JsonSerializer.CreateDefault(deserializerSettings);
JObject jsonObject = (JObject)JToken.FromObject(mySelfRefernceObject, serializer);
我继承了一个数据库应用程序,为web页面提供数据模型。默认情况下,序列化将尝试遍历整个模型树,这里的大多数答案都是如何防止这种情况的良好开端。
一个尚未探索的选项是使用接口来提供帮助。我将从之前的例子中窃取:
public partial class CompanyUser
{
public int Id { get; set; }
public int CompanyId { get; set; }
public int UserId { get; set; }
public virtual Company Company { get; set; }
public virtual User User { get; set; }
}
public interface IgnoreUser
{
[JsonIgnore]
User User { get; set; }
}
public interface IgnoreCompany
{
[JsonIgnore]
User User { get; set; }
}
public partial class CompanyUser : IgnoreUser, IgnoreCompany
{
}
在上述解决方案中,没有Json设置受到损害。将LazyLoadingEnabled和或ProxyCreationEnabled设置为false会影响所有的后端编码,并阻止ORM工具的一些真正好处。LazyLoading/ProxyCreation设置可以在不手动加载的情况下阻止导航属性的加载,这取决于您的应用程序。
这里有一个更好的解决方案,以防止导航属性序列化,它使用标准的json功能: 我怎么能做JSON序列化器忽略导航属性?
团队:
这适用于ASP。核心网;上面的挑战是如何“设置为忽略”。根据您设置应用程序的方式,这可能相当具有挑战性。以下是对我有效的方法。
这可以放在你的公共void ConfigureServices(IServiceCollection services)部分。
services.AddMvc().AddJsonOptions(opt =>
{
opt.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});