Search code examples
c#jsonjson.netattributes

Newtonsoft JSON ignore property if another property is set


I have a somewhat complex data class and in it are some properties that are related to each other. A very simple Boolean indicates whether the equally complex subclass, which is one of the properties, is used at all. This subclass uses a LOT of space in the json file and I would love to only set those values that are needed.

Normally I would just go through the code and set the complex subclass to null and add a "JsonProperty(NullValueHandling=NullValueHandling.Ignore)" as an attribute to the property. But the code is really complex and I would prefer to use an attribute and say something like "Ignore if the Boolean is false".

Is this possible? Maybe with a JsonConverter or something the like?


Solution

  • Sounds like you should use the Conditional Property Serialization based on ShouldSerialize

    So if you have a class like this;

    public class Employee
    {
        public string FirstName { get; set; }
        public string Surname { get; set; }
        public bool AddressPopulated { get; set; }
        public string Street1 { get; set; }
        public string Street2 { get; set; }
        public string Postcode { get; set; }
        public string City { get; set; }
    
      //Add should serialise here
    }
    

    And you only want to serialise if AddressPopulated is set to true, then you use this option on all the properties which are conditional and add them into your class above. Like this.

    public bool ShouldSerializeStreet1() { return AddressPopulated; }
    public bool ShouldSerializeStreet2() { return AddressPopulated; }
    public bool ShouldSerializeCity() { return AddressPopulated; }
    public bool ShouldSerializePostcode() { return AddressPopulated; }
    

    See also the documentation

    https://www.newtonsoft.com/json/help/html/conditionalproperties.htm