JSonNet对象序列化

时间:2013-04-20 15:24:48

标签: c# json.net

我在序列化中使用了“Newtonsoft.Json”。 我的应用程序中有班级“学生”和班级“教师”,当我序列化班级学生时,我必须在json代码中获得Faculty对象。

此类学生我想序列化为json。

public class Student 
            {
                public int ID { get; set; }
              **public Faculty Faculty { get; set; }
                public double AVG { get; set; }
                public DateTime DateOfBirth { get; set; }
                public string EducationInfo { get; set; }
                public string FatherName { get; set; }
                public string FirstName { get; set; }
                public string LastName { get; set; }
                public string MotherName { get; set; }
                public string Password { get; set; }
                public string PersonalInfo { get; set; }
}

班级学生内部的课程:

public class Faculty
         {
            public int id { get; set; }
            public string name { get; set; }
            public Student[] student { get; set; }
         }
序列化后

代码:

{
      "ID": 24,
      "Faculty": {
        "id": 0,
        "name": "engen",
        "student": null 
                 },
      "AVG": 3.0,
      "DateOfBirth": "1990-02-02T00:00:00",
      "EducationInfo": "GOOD",
      "FatherName": "EEWF",
      "FirstName": "FFEWR",
      "LastName": "ERF",
      "MotherName": "ERF",
      "Password": "e2DW",
      "PersonalInfo": "ERF",
     }

如何将最后一个代码转换为序列化相同的,我希望展示教师不是对象,我想要显示名称。

   {
      "ID": 24,
      "Faculty": "engen",
      "AVG": 3.0,
      "DateOfBirth": "1990-02-02T00:00:00",
      "EducationInfo": "GOOD",
      "FatherName": "EEWF",
      "FirstName": "FFEWR",
      "LastName": "ERF",
      "MotherName": "ERF",
      "Password": "e2DW",
      "PersonalInfo": "ERF",
     }

1 个答案:

答案 0 :(得分:1)

处理此问题的一种方法是使用Json.Net属性属性

试试这个:

[JsonIgnore]
public Faculty Faculty { get; set; }

[JsonProperty("Faculty")]
public string FacultyName { get { return Faculty.Name; } }

这样做的缺点是您无法将JSON反序列化回.NET对象。但是你会得到你想要的输出。