对象序列化
本文关键字:序列化 对象 | 更新日期: 2023-09-27 18:10:12
我使用"Newtonsoft "。Json"在序列化中。我的应用程序中有类"student"和类"Faculty",当我序列化类student时,我必须在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; }
}
class
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",
}
处理这个问题的一种方法是使用Json。净属性属性
试试这个:
[JsonIgnore]
public Faculty Faculty { get; set; }
[JsonProperty("Faculty")]
public string FacultyName { get { return Faculty.Name; } }
这样做的缺点是无法将JSON反序列化回。net对象。但是你会得到你想要的输出