[英]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.我正在制作一个图书馆系统,class设计( https://i.stack.imgur.com/5HlUf.png )已经提供给我们了。 These are my classes, and both have List references to each other.
这些是我的课程,两者都有 List 相互引用。 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
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.您可以在使用
ReferenceLoopHandling.Ignore
序列化时忽略自引用循环,如果 object 是其自身的子 object,则不会序列化它。 You can use it by adding it in your serializer settings:您可以通过将其添加到序列化程序设置中来使用它:
JsonConvert.SerializeObject(Author, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.