简体   繁体   中英

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. 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? 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:

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

Json.NET was exactly what I was looking for. Another option, though, is to create an anonymous type and serialize that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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