Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 455
kkocabiyik Avatar asked Apr 14 '12 01:04

kkocabiyik


1 Answers

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.

[DataContract]
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.

like image 139
nemesv Avatar answered Oct 12 '22 00:10

nemesv