简体   繁体   English

我应该如何处理C#到JSON序列化和循环引用?

[英]How should I deal with C# to JSON Serialization and circular references?

I am using the System.Web.Script.Serialization.JavaScriptSerializer contained in System.Web.Extentions DLL. 我正在使用System.Web.Extentions DLL中包含的System.Web.Script.Serialization.JavaScriptSerializer。 I have several circular references such as a basic many-to-many relationship and a parent-child relationship. 我有几个循环引用,例如基本的多对多关系和父子关系。 How can I deal with these? 我该如何处理这些? One idea we had was to replace actual object references with Foreign Keys. 我们的一个想法是用外键替换实际的对象引用。 For example, instead of this: 例如,而不是这样:

public class Node {
  public Node Parent { get; set; }
  public ICollection<Node> Children { get; set; }
}

We would do this: 我们会这样做:

public class Node {
  public long ParentID { get; set; }
  public ICollection<long> ChildrenIDs { get; set; }
}

I thought about using the ScriptIgnore Attribute but how do you even use that with Many-to-Many relationships? 我想过使用ScriptIgnore属性但是你如何在多对多关系中使用它? Advice and suggestions would be appreciated. 建议和建议将不胜感激。 Thanks! 谢谢!

Edit: Here are some example classes for the Many-to-Many Relationship. 编辑:以下是多对多关系的一些示例类。

public class Student {
  public long StudentID { get; private set; }
  public ICollection<Class> Classes { get; set; }
}

public class Class { 
  public long ClassID { get; private set; }
  public ICollection<Student> Students { get; set; }
}

The usual approach is to use [ScriptIgnore] with the parent node reference like: 通常的方法是将[ScriptIgnore]与父节点引用一起使用,如:

public class Node {
  [ScriptIgnore]
  public Node Parent { get; set; }    
  public ICollection<Node> Children { get; set; }
}

Json.NET was exactly what I was looking for. Json.NET正是我想要的。 Another option, though, is to create an anonymous type and serialize that. 但另一个选择是创建一个匿名类型并序列化它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM