We have a WCF service hosted on IIS using the DataContract Serializer (Not XmlSerializer) our need is very similar to what @Surya KLSV posted "Dynamically ignore data members from getting serialized".
Based on some business rules which we would not like to go into detail, our users can choose (by configuration) to receive, or not receive certain mambers in their answers. So we use EmitDefaultValue = false, when a user does not want to receive the BirthDate member, we assign the null value and it does not appear in the response (JSON and XML).
We are facing a problem with users who chooses to receive the member BirthDate. In some cases this value is not present in our database, it is null and when we serialize the response, this member is not appearing.
What we wanted for these cases is the member to be serialized with a null value. For users who want to receive the members:
JSON:
"Someone": {
"BirthDate": null,
"Name": "Josua",
"Age": null
}
XML:
<Someone>
<BirthDate xsi: nil = "true"/>
<Name> Josua </Name>
<Age xsi: nil = "true"/>
</Someone>
For users who do not want to receive the member
JSON:
"Someone": {
"Name": "Josua",
}
XML:
<Someone>
<Name> Josua </Name>
</Someone>
For now we are solving this in an ugly way: assigning the MinDate value on that, so this member is serialized in the response, the same for member Age, we are assigning 0 (Zero).
We can not change EmitDefaultValue = true because we will break the settings on clients that do not want to receive these members, unless, this is possible to done in runtime. Which we still can not find how to do.
We have already tried the solution from Carlos's Figueira blog but without success because the framework still respects the EmitDefaultValue
Here's an exemple to ServiceContract and DataContract:
[ServiceContract]
public interface ISomeoneService
{
[OperationContract (Name = "SearchSomeoneJson")]
[WebInvoke (Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "SearchSomeone/json?Name={name}")
Someone SearchSomeoneJson (string name);
[OperationContract (Name = "SearchSomeoneXml")]
[WebInvoke (Method = "GET", RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "SearchSomeone/xml?Name={name}")
Someone SearchSomeoneXml (string name);
}
[DataContract]
public class Someone : ISomeoneService
{
[DataMember (EmitDefaultValue = false)]
public DateTime? BirthDate {get; set; }
[DataMember (EmitDefaultValue = false)]
public string Name {get; set; }
[DataMember (EmitDefaultValue = false)]
public int? Age = null;
}