Suppose I have a class
public class Person
{
public int id { get; set; }
public string name { get; set; }
public DateTime dateOfBirth { get; set; }
}
and a second class
public class Classroom
{
public Person teacher { get; set; }
public List<Person> students { get; set; }
}
What I want to achieve is this:
When I JSON serialize a Person instance I want all properties of that person to be serialized.
But When I serialize a Classroom instance, I want only the id
and name
properties of the Person to be serialized
Example:
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' }
// ]
// }
Can i achieve that using a custom contract resolver or any other means?