Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

I am making a library system, and the class design(https://i.stack.imgur.com/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.stack.imgur.com/5HlUf.png

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading