Introduction
In this tip, I will show you a trick: how you can hide a string-type property in the serialized XML if it is empty. Empty but not null!
Background
Normally, if you use EmitDefaultValue = false on a string property, DataContractSerializer will ignore this property if it has its default value. String has the default value = null. An empty string will be serialized like e.g. <Title></Title>.
You can save a huge amount of characters, if these empty properties will be simply ignored. If in your application, it has no special meaning, if a string property is null or is empty, you can use this trick to hide empty string values.
You can save a huge amount of characters, if these empty properties will be simply ignored. If in your application, it has no special meaning, if a string property is null or is empty, you can use this trick to hide empty string values.
How to do it
We make a private property, which will be used only for the transfer.
- /// <summary>
- /// This property will be used only for transfer
- /// </summary>
- [DataMember(EmitDefaultValue = false, Name = "Title")]
- private string TitleTransfer { get; set; }
It is private, but for the DataContractSerializer it is no problem. The original property will be decorated with IgnoreDataMember, so it will not be transported.
SandyPosted Oct 6, 2017, 11:05 PM
can we do the same thing with Json?