Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Hide Empty String Property in WCF Serializing

5.00/5 (1 vote)
29 Sep 2017CPOL1 min read 11.9K  
We force to hide an empty string-property by serializing with EmitDefaultValue

Introduction

In this tip, I 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 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.

Using the Code

So we make a private property, which will be used only for the transfer.

C#
/// <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.

C++
/// <summary>
/// Title of the person.
/// It can be empty.
/// </summary>
[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

C#
var p1 = new Person() { Title = "Prof.", ForeName = "Albert", LastName = "Einstein" };

So a Person with Title will be serialized as usual.

XML
<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)...

C#
var p2 = new Person() { Title = string.Empty, ForeName = "Laszlo", LastName = "Vörös" };

...will be serialized as:

XML
<Person xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="...">
  <ForeName>Laszlo</ForeName>
  <LastName>Vörös</LastName>
</Person>

Thank you for reading!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)