Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading