Reputation: 1706
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; }
}
Upvotes: 4
Views: 1494
Reputation: 1706
Json.NET was exactly what I was looking for. Another option, though, is to create an anonymous type and serialize that.
Upvotes: 1
Reputation: 25732
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; }
}
Upvotes: 3