I have an object that contains several properties that are a List of strings List<String>
or a dictionary of strings Dictionary<string,string>
. I want to serialize the object to json using Json.net and I want to have the least amount of text generated.
I am using the DefaultValueHandling and NullValueHandling to set default values to strings and integers. But how can I define the DefaultValueHandling to ignore the property in the serialized output if it is initialized to an empty List<String>
or Dictionary<string,string>
?
Some sample output is:
{
"Value1": "my value",
"Value2": 3,
"List1": [],
"List2": []
}
I want to get a result that ignores the two lists in the above example, because they are set to the default value of an empty list.
Any help will be appreciated
Another very simple solution is to implement a ShouldSerialize*
method in the type being serialized as outline here.
This might be the preferred way if you're in control of the type being serialized and if it is not a general behavior you want to introduce.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With