0

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

我想序列化为 json 的此类 Student。

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",
     }
4

1 回答 1

1

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

尝试这个:

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

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

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

于 2013-04-20T15:29:16.450 回答