I am trying to find the best way to conditionally include and remove properties from my datacontract serialization in my .net WebApi project. In my Api, I want to allow users to specify the fields that they want returned.
For example, assume I want my API to return an instance of the following class.
public class Car
{
public int Id { get; set; }
public string Year { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public string Color { get; set; }
}
But instead of requesting the entire object, the API call wants the Id and Make field only. So the return JSON would be
{ "Id": 12345, "Make": "Ford"}
instead of the entire object.
Is there a way with the DataContract Serializer that I can conditionally add and remove properties from my return object?
**EDIT I have looked at the IgnoreDefault property, and I don't believe it will do exactly what I need. The problem is that I want to include and exclude properties based on an api request, not necessarily on whether or not they have data.
Is there some way to hook into the deserialization process and skip certain properties? Can I do some kind of custom contract?
If you're using the
DataContractSerializer
(or, in this case, theDataContractJsonSerializer
), you can use theDataMember(EmitDefaultValue = false)]
decoration in your class. This way, you can set the properties which you don't want serialized to their default values (i.e.,null
for strings, 0 for ints and so on), and they won't be.If you're using the ASP.NET Web API, then you should be aware that the default JSON serializer isn't the
DataContractJsonSerializer
(DCJS), but JSON.NET instead. So unless you explicitly configure yourJsonMediaTypeFormatter
to use DCJS, you need another attribute to get the same behavior (JsonProperty
, and itsDefaultValueHandling
property).The code below only serializes the two members which were assigned in this Car object, using both serializers. Notice that you can remove one of the attributes if you're only going to use one of them.