Is there a way to get the ShouldSerialize*
pattern working with DataContractSerializer
?
Here is a small example:
I have a simple cl
You should set the IsRequired attribute on the DataMember:
[DataContract]
public class Person
{
[DataMember(IsRequired = False, EmitDefaultValue = False)]
public string FirstName { get; set; }
...
}
AFAIK, ShouldSerialize* does not work with datacontract serializer. It is useless in the Kevin answer. You can remove it. Unfortunatly, the code given only work if you handle null value.
Here is a more generic solution: It returns null value depending of a given condition.
[DataContract]
public class Person
{
private string firstName;
[DataMember(IsRequired = false, EmitDefaultValue = false)]
public string FirstName
{
get
{
//Put here any condition for serializing
return string.IsNullOrWhiteSpace(firstName) ? null : firstName;
}
set
{
firstName = value;
}
}
}