Click or drag to resize
Json.NETConditional Property Serialization
 

Json.NET has the ability to conditionally serialize properties by placing a ShouldSerialize method on a class. This funtionality is similar to the XmlSerializer ShouldSerialize feature.

ShouldSerialize

To conditionally serialize a property add a boolean method with the same name as the property and then prefixed the method name with ShouldSerialize. The result of the method determines whether the property is serialized. If the method returns true then the property will be serialized, if it returns false and the property will be skipped.

Employee class with a ShouldSerialize method
 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}
ShouldSerialize output
 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// [
14//   {
15//     "Name": "Joe Employee",
16//     "Manager": {
17//       "Name": "Mike Manager"
18//     }
19//   },
20//   {
21//     "Name": "Mike Manager"
22//   }
23// ]
IContractResolver

ShouldSerialize can also be set using an IContractResolver. Conditionally serializing a property using an IContractResolver is useful if you don't want to place a ShouldSerialize method on a class or you didn't declare the class and are unable to.

Conditional properties with IContractResolver
 1public class ShouldSerializeContractResolver : DefaultContractResolver
 2{
 3    public new static readonly ShouldSerializeContractResolver Instance = new ShouldSerializeContractResolver();
 4
 5    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
 6    {
 7        JsonProperty property = base.CreateProperty(member, memberSerialization);
 8
 9        if (property.DeclaringType == typeof(Employee) && property.PropertyName == "Manager")
10        {
11            property.ShouldSerialize =
12                instance =>
13                {
14                    Employee e = (Employee)instance;
15                    return e.Manager != e;
16                };
17        }
18
19        return property;
20    }
21}
See Also