【问题标题】:How should I deal with C# to JSON Serialization and circular references?我应该如何处理 C# 到 JSON 序列化和循环引用?
【发布时间】:2011-06-17 14:28:31
【问题描述】:

我正在使用 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; }
}

【问题讨论】:

    标签: c# .net json serialization


    【解决方案1】:

    通常的方法是使用带有父节点引用的 [ScriptIgnore],例如:

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

    【讨论】:

    • 我该如何处理多对多关系?
    • 为此,您必须使用 Json.NET。它的最新版本支持序列化循环 n 对 n 关系。在帮助中查看Preserving Object References
    【解决方案2】:

    Json.NET 正是我想要的。不过,另一种选择是创建一个匿名类型并将其序列化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-30
      • 1970-01-01
      • 2021-10-20
      相关资源
      最近更新 更多