Json.NET在将对象序列化为Json字符串的时候,如果对象有循环引用的属性或字段,那么会导致Json.NET抛出循环引用异常。

 

有两种方法可以解决这个问题:

1、在对象循环引用的属性上打上[JsonIgnore]标签,例如:

public class UserProfile
{
    public string UserCode { get; set; }
    public string UserName { get; set; }
    public string MailAddress { get; set; }
    public long LoginTimeStamp { get; set; }

    [JsonIgnore]
    protected List<Role> roles;

    [JsonIgnore]
    public List<Role> Roles
    {
        get
        {
            return roles;
        }
    }
}

 

2、另一个方法是在调用Json.NET的SerializeObject方法序列化对象时,设置ReferenceLoopHandling属性为ReferenceLoopHandling.Ignore,如下所示:

var stringObject = JsonConvert.SerializeObject(value, new JsonSerializerSettings()
{
    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});

这样Json.NET检测到循环引用时,就会停止序列化操作,忽略对象的循环引用属性

 

相关文章:

  • 2021-09-26
  • 2022-12-23
  • 2021-12-23
  • 2021-11-26
  • 2021-11-23
  • 2021-05-31
  • 2021-08-03
  • 2022-12-23
猜你喜欢
  • 2021-11-13
  • 2021-08-14
  • 2021-09-11
  • 2021-11-15
  • 2022-12-23
  • 2022-02-27
  • 2021-08-11
相关资源
相似解决方案