JSON.NET Error Self referencing loop detected for type

我们在使用JsonConvert.SerializeObject 把对象转换为json格式出现以下错误

其他信息: Self referencing loop detected for property


解决办法如下:

Use JsonSerializerSettings

  • ReferenceLoopHandling.Error (default) will error if a reference loop is encountered. This is why you get an exception.
  • ReferenceLoopHandling.Serialize is useful if objects are nested but not indefinitely.
  • ReferenceLoopHandling.Ignore will not serialize an object if it is a child object of itself.

Example:

JsonConvert.SerializeObject(YourPOCOHere, Formatting.Indented, 
new JsonSerializerSettings { 
        ReferenceLoopHandling = ReferenceLoopHandling.Serialize
});

Should you have to serialize an object that is nested indefinitely you can use PreserveObjectReferences to avoid a StackOverflowException.

Example:

JsonConvert.SerializeObject(YourPOCOHere, Formatting.Indented, 
new JsonSerializerSettings { 
        PreserveReferencesHandling = PreserveReferencesHandling.Objects
});



MVC4解决如下:

json.net serializer supports to ignore circular reference on global setting. A quick fix is to put following code inWebApiConfig.cs file:

 config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling 
= Newtonsoft.Json.ReferenceLoopHandling.Ignore; 

The simple fix will make serializer to ignore the reference which will cause a loop. However, it has limitations:

The data loses the looping reference information The fix only applies to JSON.net The level of references can't be controlled if there is a deep reference chain Fix 2: Preserving circular reference globally

This second fix is similar to the first. Just change the code to:

config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling 
     = Newtonsoft.Json.ReferenceLoopHandling.Serialize;     
config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling 
     = Newtonsoft.Json.PreserveReferencesHandling.Objects;

The data shape will be changed after applying this setting.

[
   {
      "$id":"1",
      "Category":{
         "$id":"2",
         "Products":[
            {
               "$id":"3",
               "Category":{
                  "$ref":"2"
               },
               "Id":2,
               "Name":"Yogurt"
            },
            {
               "$ref":"1"
            }
         ],
         "Id":1,
         "Name":"Diary"
      },
      "Id":1,
      "Name":"Whole Milk"
   },
   {
      "$ref":"3"
   }
]

The $id and $ref keeps the all the references and makes the object graph level flat, but the client code needs to know the shape change to consume the data and it only applies to JSON.NET serializer as well.

Fix 3: Ignore and preserve reference attributes

This fix is decorate attributes on model class to control the serialization behavior on model or property level. To ignore the property:

1: public class Category 
   2: { 
   3:     public int Id { get; set; } 
   4:     public string Name { get; set; } 
   5:     
   6:     [JsonIgnore] 
   7:     [IgnoreDataMember] 
   8:     public virtual ICollection<Product> Products { get; set; } 
   9: } 

JsonIgnore is for JSON.NET and IgnoreDataMember is for XmlDCSerializer. To preserve reference:

1: // Fix 3 
   2: [JsonObject(IsReference = true)] 
   3: public class Category 
   4: { 
   5:     public int Id { get; set; } 
   6:     public string Name { get; set; } 
   7:  
   8:     // Fix 3 
   9:     //[JsonIgnore] 
  10:     //[IgnoreDataMember] 
  11:     public virtual ICollection<Product> Products { get; set; } 
  12: } 
  13:  
  14: [DataContract(IsReference = true)] 
  15: public class Product 
  16: { 
  17:     [Key] 
  18:     public int Id { get; set; } 
  19:  
  20:     [DataMember] 
  21:     public string Name { get; set; } 
  22:  
  23:     [DataMember] 
  24:     public virtual Category Category { get; set; } 
  25: } 

JsonObject(IsReference = true)]is for JSON.NET and [DataContract(IsReference = true)] is for XmlDCSerializer. Note that: after applyingDataContract on class, you need to add DataMember to properties that you want to serialize.





  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值