假设我有一个班级
public class Person
{
public int id { get; set; }
public string name { get; set; }
public DateTime dateOfBirth { get; set; }
}
和第二课
public class Classroom
{
public Person teacher { get; set; }
public List<Person> students { get; set; }
}
我想要实现的目标是:
当我JSON序列化一个Person实例时,我希望序列化该人的所有属性。
但是当我序列化一个Classroom实例时,我只希望序列化Person的id
和name
属性
示例:
var teacher = new Person { id = 0, name = "Anna", dateOfBirth = new Datetime(1989, 10, 1) }
var student1 = new Person { id = 1, name = "Nick", dateOfBirth = new Datetime(2009, 4, 14) }
var student2 = new Person { id = 2, name = "Helen", dateOfBirth = new Datetime(2009, 6, 23) }
var classRoom = new Classroom
{
teacher = teacher,
students = new List<Student> { student1, student2 }
}
var techerJson = JsonConvert.Serialize(teacher, ...)
var studentJson = JsonConvert.Serialize(student1, ...)
var classRoomJson = JsonConvert.Serialize(classRoom, ...)
// techerJson == { id: 0, name: 'Anna', dateOfBirth: '1989-10-01T00:00:00' }
// studentJson == { id: 1, name: 'Nick', dateOfBirth: '2009-04-14T00:00:00' }
// classRoomJson ==
// {
// teacher: { id: 0, name: 'Anna' },
// students: [
// { id: 1, name: 'Nick' },
// { id: 2, name: 'Helen' }
// ]
// }
我可以使用自定义合约解析程序或任何其他方式实现这一目标吗?