Click or drag to resize
Json.NETSerialize Conditional Property
 

This sample uses a conditional property to exclude a property from serialization.

Sample
Types
 1public class Employee
 2{
 3    public string Name { get; set; }
 4    public Employee Manager { get; set; }
 5
 6    public bool ShouldSerializeManager()
 7    {
 8        // don't serialize the Manager property if an employee is their own manager
 9        return (Manager != this);
10    }
11}
Usage
 1Employee joe = new Employee();
 2joe.Name = "Joe Employee";
 3Employee mike = new Employee();
 4mike.Name = "Mike Manager";
 5
 6joe.Manager = mike;
 7
 8// mike is his own manager
 9// ShouldSerialize will skip this property
10mike.Manager = mike;
11
12string json = JsonConvert.SerializeObject(new[] { joe, mike }, Formatting.Indented);
13
14Console.WriteLine(json);
15// [
16//   {
17//     "Name": "Joe Employee",
18//     "Manager": {
19//       "Name": "Mike Manager"
20//     }
21//   },
22//   {
23//     "Name": "Mike Manager"
24//   }
25// ]