而序列化类型的对象检测JSON循环引用 [英] Json A circular reference was detected while serializing an object of type
问题描述
使类:
公共类父
{
公众诠释ID {搞定;设置;}
公众诠释名称{;设置;}
公共虚拟的ICollection<儿童>儿童{搞定;设置;}
}
表(子)]
公共部分类儿童
{
[关键]
公众诠释ID {搞定;设置;}
公共字符串名称{;组; }
[NotMapped]
公共字符串昵称{搞定;组; }
}
和控制器代码:
列表<家长和GT;父母= parentRepository.Get();
返回JSON(父母);
它工作在本地主机,但它不会活的服务器上运行:
错误:被同时序列化类型的对象检测的Json循环引用
块引用>
我做了搜索,发现了
[ScriptIgnore]
属性,所以我改变了模型使用System.Web.Script.Serialization;
公共类父
{
公众诠释ID {搞定;设置;}
公众诠释名称{;设置;}
[ScriptIgnore]
公共虚拟的ICollection<儿童>儿童{搞定;设置;}
}
但同样的错误发生的现场服务器(WIN2008)上<。 / p>
我如何避免该错误并成功序列化父数据?
解决方案试试下面的代码:
返回JSON(
parents.Select(X =>新建{
ID = x.id,
NAME = x.name,
=儿童x.children.Select(Y =>儿童的新{
// Assigment字段
})
}));
只有父属性:
返回JSON(
parents.Select(X =>新建{
ID = x.id,
NAME = x.name
}) );
的这是不是真的该问题的解决方案,但序列化时,它是一种常见的解决方法DTO的... 的
Give the classes:
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; } }
And the controller code:
List<Parent> parents = parentRepository.Get(); return Json(parents);
It works on LOCALHOST, but it does not work on live server:
ERROR : Json A circular reference was detected while serializing an object of type
I did a search and found the
[ScriptIgnore]
attribute, so I changed the model tousing 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;} }
But the same error occur on live server (win2008).
How can I avoid that error and serialize the parent data successfully?
解决方案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 }) }));
Only 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...
这篇关于而序列化类型的对象检测JSON循环引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!