1

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?

Thanasis Ioannidis
  • 2,981
  • 1
  • 30
  • 50
  • Duplicate? [Json.NET serialize by depth and attribute](https://stackoverflow.com/q/36159424/3744182). – dbc Aug 01 '17 at 09:50
  • I always define classes for the JSON serialization. Just following [SRP](https://en.wikipedia.org/wiki/Single_responsibility_principle) – Sir Rufo Aug 01 '17 at 09:57
  • @dbc it may be duplicate yes. I will take a look at it. I also want to dynamically choose the fields to serialize (or not) at runtime based on user input. – Thanasis Ioannidis Aug 01 '17 at 11:08
  • 1
    @ThanasisIoannidis - *I also want to dynamically choose the fields to serialize (or not) at runtime based on user input.* -- that's not what your question is asking. You may need to ask another question or at least [edit] and rewrite this one. Maybe you're actually looking for [How to perform partial object serialization providing “paths” using Newtonsoft JSON.NET](https://stackoverflow.com/q/30304128) or [How to do partial responses using ASP.Net Web Api 2](https://stackoverflow.com/q/20059191)? – dbc Aug 01 '17 at 22:21

0 Answers0