Serializing only populated properties

May 26, 2009 at 4:14 PM
I have a json like this:
"EB": [
{
"Id": "30",
"Type": "Active Coverage",
"Service": "Health Benefit Plan Coverage",
"Description": "CHOICE PLUS",
"Authorization": ""
},
{
"Id": "35",
"Type": "Active Coverage",
"Service": "Dental Care",
"Description": "",
"Authorization": ""
}
]

Is it possible to omit Json from generating those empty properties? The result should look like this :

"EB": [
{
"Id": "30",
"Type": "Active Coverage",
"Service": "Health Benefit Plan Coverage",
"Description": "CHOICE PLUS"
},
{
"Id": "35",
"Type": "Active Coverage",
"Service": "Dental Care"
}
]

Thanks
May 26, 2009 at 5:19 PM

I found it:

Here is the code:

            JsonSerializerSettings jss = new JsonSerializerSettings();
            jss.NullValueHandling = NullValueHandling.Ignore;
            return JsonConvert.SerializeObject(EW, Formatting.None, jss);

Oct 19, 2009 at 2:29 PM

This only appears to work if the default value for a properties backing string is Nothing:

Dim _foo As String

If you happen to have variables that are declared as empty strings (in a class you don't control)

Dim _foo As String = String.Empty

They still get serialized as "", even with the NullValueHandling.Ignore and DefaultValueHandling.Ignore set.

Is there way to ignore both Nothing and String.Empty  for string properties, regardless of what the .NET default is?

 

Coordinator
Oct 24, 2009 at 1:31 AM

Mark the property with [DefaultValue("")]

See this blog post for more info - http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size.aspx

Oct 24, 2009 at 1:56 AM
Nice article. Just what I needed. Thanks!