DefaultValueHandling setting |
This sample uses the DefaultValueHandling setting to not serialize properties with a default value.
public class Person { public string Name { get; set; } public int Age { get; set; } public Person Partner { get; set; } public decimal? Salary { get; set; } }
Person person = new Person(); string jsonIncludeDefaultValues = JsonConvert.SerializeObject(person, Formatting.Indented); Console.WriteLine(jsonIncludeDefaultValues); // { // "Name": null, // "Age": 0, // "Partner": null, // "Salary": null // } string jsonIgnoreDefaultValues = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore }); Console.WriteLine(jsonIgnoreDefaultValues); // {}