We are looking at converting our currently in development WCF REST API to use the new ASP.NET MVC 4 Web API because it simplifies a number of things. One thing I like about WCF is the ability to add a [DataMember(EmitDefaultValue=false)] attribute to data contracts so that certain values that aren’t set, will not be serialized back on JSON/XML objects.
Is there an equivalent to this function in the new ASP.NET MVC 4 Web API? I can’t seem to find anything regarding this.
Depending on the serialization mechanism ASP.NET Web API will use a different serializer. Currently in the beta for JSON it will use a JavaScriptSerializer and for XML it uses XmlSerializer. But there’s a
UseDataContractSerializerproperty on the XmlMediaTypeFormatter which allows you to use the same XML serializer as in WCF (DataContractFormatter).I don’t think that there is an unique way by just decorating your model with some attribute to make those 2 serializer behave the same way unless writing some custom media type formatter. So one possibility is to write custom formatters for XML/JSON and swap the serializer being used to those used in WCF.
Here’s an example of such formatter which uses JSON.Net for JSON. You could adapt it so that it uses DataContractJsonSerializer which will take into account the
EmitDefaultValueproperty.