Serialize Nullable<T> or not

When we tried to serialize an object to XML we noticed that Nullable types are special. A class is not serialized when null, but a Nullable type is a struct. See the code blow and notice the highlighted line in the output.

class Program
{
    static void Main(string[] args)
    {
        var obj = new MyType();
        var serializer = new XmlSerializer(typeof(MyType));
        serializer.Serialize(Console.Out, obj);
        Console.ReadLine();
    }
}

[Serializable]
public class MyType
{
    public string        MyStringProperty      { get; set; }
    public int           MyIntProperty         { get; set; }
    public Nullable<int> MyNullableIntProperty { get; set; }
}

Unwanted output:

<?xml version="1.0" encoding="ibm850"?>
<MyType>
  <MyIntProperty>0</MyIntProperty>
  <MyNullableIntProperty xsi:nil="true" />
</MyType>

The dotnet framework has a trick up its sleeve. Use the ShouldSerialize{PropertyName} function to manipulate the way a property is serialized. The corrected class is below. Using the same program the output now was without the (ugly) line of the nullable property.

[Serializable]
public class MyType
{
    public string        MyStringProperty      { get; set; }
    public int           MyIntProperty         { get; set; }
    public Nullable<int> MyNullableIntProperty { get; set; }
    // do not serialize MyNullableIntProperty if it has not been set
    public bool ShouldSerializeMyNullableIntProperty() 
    { 
        return MyNullableIntProperty.HasValue; 
    }
}

Correct output:

<?xml version="1.0" encoding="ibm850"?>
<MyType>
  <MyIntProperty>0</MyIntProperty>
</MyType>

About erictummers

Working in a DevOps team is the best thing that happened to me. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Development and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.