【问题标题】:Serialize nested objects(list)序列化嵌套对象(列表)
【发布时间】:2015-11-17 09:08:07
【问题描述】:

我正在尝试序列化课程的数据。我得到课程 ID(C_id)和课程名称(C_Name)。我得到的另一件事是学生的 Icoolection。当我尝试对其进行序列化时,我无法获得已注册该课程的学生的嵌套列表。

var u = (from g in t.courses 
         select g)
        .ToList();

List<course> ui = u
    .Select(d => new course() 
        { C_Name = d.C_Name, 
          C_Id = d.C_Id, 
          student = d.student 
        })
    .ToList();

ASCIIEncoding objASCIIEncoding = new ASCIIEncoding();

string strData = JsonConvert
    .SerializeObject(ui, Formatting.Indented, new JsonSerializerSettings()
{
    ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
});

在上面的代码中,我使用嵌套的students 列表获得了正确的数据,但是当这一行时

string strData = JsonConvert.SerializeObject(ui, Formatting.Indented, new JsonSerializerSettings()
{
    ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
});

执行我只得到 Course ID(C_ID) 和 course Name(C_Name) 。嵌套的student 列表未序列化。

【问题讨论】:

标签: c# entity-framework


【解决方案1】:

来自文档:

Json.NET 将忽略引用循环中的对象并且不序列化 他们。第一次遇到对象时,它将被序列化为 通常,但如果对象作为其自身的子对象遇到 序列化程序将跳过序列化它。

http://james.newtonking.com/json/help/index.html?topic=html/SerializationSettings.htm

我假设您的学生包含对他们课程的引用?也许您应该通过执行类似于以下的操作来确保他们不会删除对课程的引用:

student = d.student.Select(s => new {s.studentId, s.studentName}).ToList()

【讨论】:

    【解决方案2】:

    希望这有助于http://www.newtonsoft.com/json/help/html/PreserveObjectReferences.htm

    JsonSerializer 上的 PreserveReferencesHandling 设置将改变所有对象的序列化和反序列化方式。对于应将哪些对象和成员序列化为引用的细粒度控制,JsonObjectAttribute、JsonArrayAttribute 和 JsonPropertyAttribute 上有 IsReference 属性。 将 JsonObjectAttribute 或 JsonArrayAttribute 上的 IsReference 设置为 true 将意味着 JsonSerializer 将始终序列化该属性所针对的类型作为参考。将 JsonPropertyAttribute 上的 IsReference 设置为 true 将仅将该属性序列化为引用。

    [JsonObject(IsReference = true)]
    public class EmployeeReference
    {
        public string Name { get; set; }
        public EmployeeReference Manager { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-08
      • 1970-01-01
      • 2016-06-29
      • 1970-01-01
      相关资源
      最近更新 更多