Removing Null Properties from Json in MVC Web Api 4 Beta

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.


The ASP.NET Web API currently (there are plans to change it for the final release to use Json.Net) uses DataContractJsonSerializer by default to serialize JSON.

So you can control the serialization process with the standard DataContract/DataMember attributes. To skip null properties you can set the EmitDefaultValue to false.

public class MyObjet
    [DataMember(EmitDefaultValue = false)]
    public string Prop1 { get; set; }

    [DataMember(EmitDefaultValue = false)]
    public string Prop2 { get; set; }

If you want to have more control on how the JSON responses are serialized you can use the WebAPIContrib package which contains formatters using Json.Net or the built in JavaScriptSeralizer.

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.

Need Your Help

How to enable hotspot service on jailbroken ios device

ios root jailbreak tether

I am trying to turn Personal Hotspot service on/off programmatically.

jhipster session timeout configuration

spring security angularjs jhipster

I downloaded JHipster from git and tried to understand how to configure session timeout but couldn't find any web.xml or java-based class for that.