Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Json.Net skip serialization of empty collections

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

like image 438
agarcian Avatar asked Aug 27 '13 17:08

agarcian


1 Answers

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.

like image 181
Dejan Avatar answered Sep 30 '22 03:09

Dejan