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.
[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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With