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.
How to do it
We make a private property, which will be used only for the transfer.
-
-
-
- [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.
-
-
-
-
- [IgnoreDataMember]
- public string Title
- {
- get { return this.TitleTransfer ?? string.Empty; }
- set
- {
- this.TitleTransfer = String.IsNullOrEmpty(value) ? null : value;
- }
- }
In the setter of the original property, I set the transfer-property to null, if the value would be empty. So the transfer-property will never be empty but null.
Test it!
- var p1 = new Person() { Title = "Prof.", ForeName = "Albert", LastName = "Einstein" };
So a Person with Title will be serialized as usual.
- <Person xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="...">
- <ForeName>Albert</ForeName>
- <LastName>Einstein</LastName>
- <Title>Prof.</Title>
- </Person>
But a Person without Title (empty)...
- var p2 = new Person() { Title = string.Empty, ForeName = "Laszlo", LastName = "Vörös" };
... will be serialized like this:
- <Person xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="...">
- <ForeName>Laszlo</ForeName>
- <LastName>Vörös</LastName>
- </Person>