码迷,mamicode.com
首页 > Web开发 > 详细

Json.NET如何避免循环引用

时间:2019-01-18 21:20:35      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:div   ring   字符   ref   get   cte   address   add   ack   

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检测到循环引用时,就会停止序列化操作,忽略对象的循环引用属性

 

Json.NET如何避免循环引用

标签:div   ring   字符   ref   get   cte   address   add   ack   

原文地址:https://www.cnblogs.com/OpenCoder/p/10289667.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!