由于自引用循环,C# 无法序列化我的对象

C# Can't serialize my object because of self-referencing loops

我正在做一个图书馆系统,class设计(https://i.stack.imgur.com/5HlUf.png)已经提供给我们了。 这些是我的 classes,两者都有 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 序列化时忽略 self-referencing 循环,如果对象是其自身的子对象,则不会序列化该对象。您可以通过在序列化程序设置中添加它来使用它:

JsonConvert.SerializeObject(Author, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore});