Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't XmlSerializer support Dictionary?

Just curious as to why Dictionary is not supported by XmlSerializer?

You can get around it easily enough by using DataContractSerializer and writing the object to a XmlTextWriter, but what are the characteristics of a Dictionary that makes it difficult for a XmlSerializer to deal with considering it's really an array of KeyValuePairs.

In fact, you can pass an IDictionary<TKey, TItem> to a method expecting an IEnumerable<KeyValuePairs<TKey, ITem>>.

like image 465
theburningmonk Avatar asked May 26 '10 09:05

theburningmonk


People also ask

Can dictionary be serialized in C#?

The serialization and deserialization of . NET objects is made easy by using the various serializer classes that it provides. But serialization of a Dictionary object is not that easy. For this, you have to create a special Dictionary class which is able to serialize itself.

Is XmlSerializer thread safe?

Since XmlSerializer is one of the few thread safe classes in the framework you really only need a single instance of each serializer even in a multithreaded application. The only thing left for you to do, is to devise a way to always retrieve the same instance.

Why do we use XmlSerializer class?

XmlSerializer enables you to control how objects are encoded into XML. The XmlSerializer enables you to control how objects are encoded into XML, it has a number of constructors.

How does the XmlSerializer work C#?

The XmlSerializer creates C# (. cs) files and compiles them into . dll files in the directory named by the TEMP environment variable; serialization occurs with those DLLs. These serialization assemblies can be generated in advance and signed by using the SGen.exe tool.


2 Answers

Hashtables need hashcode and equality comparer providers generally. These cant be serialized easily in XML, and definitely will not be portable.

But I think you already found your answer. Just serialize the hashtable as a List<KeyValuePair<K,V>> and then (re)construct it into a hashtable.

like image 151
leppie Avatar answered Sep 22 '22 05:09

leppie


This is waaay late - but I found this question whilst looking for the answer myself, and thought I'd share my eventual answer which was to replace XmlSerializer with a different tool that will serialize everything:

http://www.sharpserializer.com

It worked for me straight out of the box, serializing Dictionaries, and multi-layered custom types, and even generics using interfaces as type arguments. Also has a fully permissive license.

Thank you Pawel Idzikowski!

like image 33
Nich Overend Avatar answered Sep 26 '22 05:09

Nich Overend