Alex Rivera | Logout

Removing Null Properties from Json in MVC Web Api 4 Beta

Asked 2012-04-14T01:43:46.757
14

I'm serializing objects and returning as json from my web service. However, I'm trying to omit null properties from serialized json. Is there a way to do this? I'm using Web Api MVC 4 beta.

Edit
Report

1 Answer

10

In Json.Net you can use JsonPropertyAttribute with NullValueHandling=NullValueHandling.Ignore. Looks like here is no way to do this for whole class, only explicity for each class field/property.

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string SometimesNull { get; set; }

FYI. There is a reasons why Json.Net by default serialize properties with null values. Take a look, may be some of this reasons applicable to your cases.

answered 2013-06-03T15:47:17.133

Your Answer