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

时间:2013-01-29 21:38:07

标签: c# json dto

提供课程:

public class Parent
{
    public int id {get; set;}
    public int name {get; set;}

    public virtual ICollection<Child> 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<Parent> 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<Child> children {get; set;}
}

但在实时服务器(win2008)上会出现同样的错误。

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

4 个答案:

答案 0 :(得分:47)

请尝试以下代码:

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时这是一个常见的解决方法......

答案 1 :(得分:2)

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

我确实在A circular reference was detected while serializing with Json.Encode

发布了问题和解决方案

我用mvchelper解决了。

答案 2 :(得分:2)

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

.m2

答案 3 :(得分:1)

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

行动

return Json(ModelHelper.GetJsonModel<Core_User>(viewModel));

功能

   public static TEntity GetJsonModel<TEntity>(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_;  
    }