Json A circular reference was detected while serializing an object of type

岁酱吖の 提交于 2019-11-29 01:10:39

Try the following code:

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

...or if you only need the parent properties:

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

It is not really the solution for the problem, but it is a common workaround when serializing DTOs...

David

I had a similar issue and likewise i was not able to resolve the underlying issue. I figure the server is using a dll different from localhost for the conversion to json via json.encode.

I did post the question and my resolution here A circular reference was detected while serializing with Json.Encode

I resolved with mvchelper.

You could use this code and do not use select Extention function to filter your column.

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

I'm Using the fix, Because Using Knockout in MVC5 views.

On action

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

function

   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_;  
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!