.Net Tips — Xml Serialize or Deserialize Dictionary in C#

Yan Cui
theburningmonk.com
Published in
2 min readMay 30, 2010

If you try to serialize/deserialize a type which uses the generic Dictionary<TKey, TValue> type with the XmlSerializer then you’ll get an InvalidOperationException, for instance:

Here’s my class:

[code lang=”csharp”]
public class MyClass
{
// need a parameterless constructor for serialization
public MyClass()
{
MyDictionary = new Dictionary<string, string>();
}
public Dictionary<string, string> MyDictionary { get; set; }
}
[/code]

I’ll get an InvalidOperationException with an inner exception of type NotSupportedException when I do this:

[code lang=”csharp”]
var xmlSerializer = new XmlSerializer(typeof(MyClass));
[/code]

And the error message of the NotSupportedException is:

“Cannot serialize member MyClass.MyDictionary of type System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], because it implements IDictionary.”

The reason why Dictionary<TKey, TValue> is not supported by the XmlSerializer is that types such as Dictionary, HashTable, etc. needs an equality comparer which can’t be serialized into XML easily and won’t be portable anyhow. To get around this problem, you generally have two options, in the order of my personal preference:

Use DataContractSerizalizer

The easiest, and cleanest solution is to switch over to data contract serialization, and the only change required would be to mark your class with the DataContractAttribute and mark the properties you want to serialize with the DataMemberAttribute. My class would now look like this:

[code lang=”csharp”]
[DataContract]
public class MyClass
{
// need a parameterless constructor for serialization
public MyClass()
{
MyDictionary = new Dictionary<string, string>();
}
[DataMember]
public Dictionary<string, string> MyDictionary { get; set; }
}
[/code]

And to serialize it into Xml, just use the DataContractSerializer and write the output with a XmlTextWriter like this:

[code lang=”csharp”]
var serializer = new DataContractSerializer(typeof(MyClass));
string xmlString;
using (var sw = new StringWriter())
{
using (var writer = new XmlTextWriter(sw))
{
writer.Formatting = Formatting.Indented; // indent the Xml so it’s human readable
serializer.WriteObject(writer, marketplace);
writer.Flush();
xmlString = sw.ToString();
}
}
[/code]

Use a custom Dictionary type

The alternative is to create your own Dictionary implementation which is Xml serializable. See the references section for an implementation Paul Welter has created.

References:

XML Serializable Generic Dictionary

--

--

Yan Cui
theburningmonk.com

AWS Serverless Hero. Follow me to learn practical tips and best practices for AWS and Serverless.