One of the least explored feature of Newtonsoft Json is the ability serialize properties conditionally. Consider the hypothetical situation wherein you want to serialize a property in a class only if a condition is satisfied. For example,
public class User { public string Name {get;set;} public string Department {get;set;} public bool IsActive {get;set;} }
If the requirement is that you need to include serialize the Department Property only if the User Is Active, then the easiest way to do it would be to use the Conditional Serialization functionality of Json.Net. All you need to do is include a method that
a) Returns a boolean indicating whether to serialize or not.
b) Should be named with Property named prefixed with ‘ShouldSerialize’
For example, for the Property Department, the method should be named ‘ShouldSerializeDepartment’. Example,
public bool ShouldSerializeDepartment()=> IsActive;
Complete Code
public class User { public string Name {get;set;} public string Department{get;set;} public bool IsActive {get;set;} public bool ShouldSerializeDepartment()=> IsActive; }
Client Code
var user = new User{ Name = "Anu Viswan", IsActive = false} ; var result = JsonConvert.SerializeObject(user);
Output
{"Name":"Anu Viswan","IsActive":false}