[英]C# Can't serialize my object because of self-referencing loops
我正在制作一個圖書館系統,class設計( https://i.stack.imgur.com/5HlUf.png )已經提供給我們了。 這些是我的課程,兩者都有 List 相互引用。 當我嘗試序列化它們時,我遇到了自引用循環異常。 我明白為什么會出現這個問題,只是不知道如何解決。
class Author
{
public Author(int AuthorID, string Name, int YearOfBirth, List<Book> Books,string Country)
{
this.AuthorID = AuthorID;
this.Name = Name;
this.YearOfBirth = YearOfBirth;
this.Books = Books;
this.Country = Country;
}
public int AuthorID { get; private set; }
public string Name { get; private set; }
public int YearOfBirth { get; private set; }
//[JsonIgnore]
public List<Book> Books { get; private set; }
public string Country { get; private set; }
}
class Book
{
public Book() { }
public Book(int ISBN, string Title, string Genre, List<Author> Authors, int Year, string Description)
{
this.ISBN = ISBN;
this.Title = Title;
this.Genre = Genre;
this.Authors = Authors;
this.Year = Year;
this.Description = Description;
}
public int ISBN { get; private set; }
public string Title { get; private set; }
public string Genre { get; private set; }
//[JsonIgnore]
public List<Author> Authors { get; private set; }
public int Year { get; private set; }
public string Description { get; private set; }
```
[1]: https://i.stack.imgur.com/5HlUf.png
您可以在使用ReferenceLoopHandling.Ignore
序列化時忽略自引用循環,如果 object 是其自身的子 object,則不會序列化它。 您可以通過將其添加到序列化程序設置中來使用它:
JsonConvert.SerializeObject(Author, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.