Search code examples
c#json.netconsole-applicationself-reference

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


I am making a library system, and the class design(https://i.sstatic.net/5HlUf.png) has already been provided to us . These are my classes, and both have List references to each other. When I try to serialize them, I am faced with a self-referencing loop exception. I understand why the problem exists, I just don't know how to solve it.

 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.sstatic.net/5HlUf.png

Solution

  • You can ignore the self-referencing loops while serializing by using ReferenceLoopHandling.Ignore which will not serialize an object if it is a child object of itself. You can use it by adding it in your serializer settings:

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