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

标签 c# .net json serialization

我正在使用 System.Web.Extentions DLL 中包含的 System.Web.Script.Serialization.JavaScriptSerializer。我有几个循环引用,例如基本的多对多关系和父子关系。我该如何处理这些?我们的一个想法是用外键替换实际的对象引用。例如,而不是这个:

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

我们会这样做:

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

我考虑过使用 ScriptIgnore 属性,但您如何将它用于多对多关系?意见和建议将不胜感激。谢谢!

编辑:这里有一些多对多关系的示例类。

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; }
}

最佳答案

通常的方法是将 [ScriptIgnore] 与父节点引用一起使用,例如:

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

关于c# - 我应该如何处理 C# 到 JSON 序列化和循环引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6387346/

相关文章:

c# - 从分钟转换为毫秒,然后转换为 Int

c# - 我应该如何将控制字符添加到字符串

.net - 使用托管数组和 std :array at same time 不兼容

python - 将特定的 pydantic 对象字段设置为 null 时不序列化

ios - 性能缓慢 Json 图像分辨率

c# - 在 wpf 中运行视频

c# - 无法将 List<string> 从方法 1 传递到方法 2

c# - System.Data.dll 上系统程序集的 .NET 反射失败

python - 在具有确切名称的不同 json 文件中搜索确切的字符串值

c# - 列出 Azure 表值