Json序列化类型的对象时检测到循环引用

给课程:

public class Parent { public int id {get; set;} public int name {get; set;} public virtual ICollection children {get; set;} } [Table("Child")] public partial class Child { [Key] public int id {get; set;} public string name { get; set; } [NotMapped] public string nickName { get; set; } } 

和控制器代码:

 List parents = parentRepository.Get(); return Json(parents); 

它适用于LOCALHOST,但它不适用于实时服务器:

错误: Json序列化类型的对象时检测到循环引用

我进行了搜索并找到了[ScriptIgnore]属性,因此我将模型更改为

 using System.Web.Script.Serialization; public class Parent { public int id {get; set;} public int name {get; set;} [ScriptIgnore] public virtual ICollection children {get; set;} } 

但在实时服务器(win2008)上发生同样的错误。

如何避免该错误并成功序列化父数据?

请尝试以下代码:

 return Json( parents.Select(x => new { id = x.id, name = x.name, children = x.children.Select(y => new { // Assigment of child fields }) })); 

…或者如果您只需要父属性:

 return Json( parents.Select(x => new { id = x.id, name = x.name })); 

它不是问题的解决方案,但在序列化DTO时这是一个常见的解决方法……

我有类似的问题,同样我也无法解决潜在的问题。 我认为服务器正在使用与localhost不同的dll通过json.encode转换为json。

我在这里发布了问题和我的解决方案在使用Json.Encode进行序列化时检测到循环引用

我用mvchelper解决了。

您可以使用此代码,不要使用select Extention函数来过滤列。

 var list = JsonConvert.SerializeObject(Yourmodel, Formatting.None, new JsonSerializerSettings() { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore }); return list; 

我正在使用修复,因为在MVC5视图中使用Knockout。

在行动

 return Json(ModelHelper.GetJsonModel(viewModel)); 

function

  public static TEntity GetJsonModel(TEntity Entity) where TEntity : class { TEntity Entity_ = Activator.CreateInstance(typeof(TEntity)) as TEntity; foreach (var item in Entity.GetType().GetProperties()) { if (item.PropertyType.ToString().IndexOf("Generic.ICollection") == -1 && item.PropertyType.ToString().IndexOf("SaymenCore.DAL.") == -1) item.SetValue(Entity_, Entity.GetPropValue(item.Name)); } return Entity_; }