使用Json.Net 序列化 时候 出现 " Self referencing loop detected for type "错误
代码:
1 public class Product 2 { 3 public Product() 4 { 5 Items = new List<ProductItem>(); 6 } 7 8 public int ProductID { get; set; } 9 public string ProductName { get; set; } 10 11 12 public List<ProductItem> Items { get; set; } 13 } 14 15 public class ProductItem 16 { 17 public Product Owner { get; set; } 18 public int ItemID { get; set; } 19 }
解决办法:
1、使用 Json.Net 自带的 attribute "JsonIgnore" ,则该字段不序列化。
[JsonIgnore] public Product Owner { get; set; }
2、修改字段修饰符 为 internal
internal Product Owner { get; set; }
也可以将相应属性改成方法,也可以使用自定义IContractResolver来处理
使用.net 自带的序列化也会出现类似错误,处理方法类似,标记以备后查。