Json.NET如何避免循環引用
阿新 • • 發佈:2019-01-18
address var amp 對象序列化 兩種方法 問題: 一個 就會 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如何避免循環引用