Possible Duplicate:
Serialize Class containing Dictionary member
Can I serialize a Dictionary?
[C#] Dictionary with duplicate keys The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.
Dictionary can't be serialized as a document.
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.
Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.
Which serialization API?
For example, DataContractSerializer
can handle dictionaries, especially with the (optional) [CollectionDataContract]
markup. protobuf-net will handle them (below). Others may not...
var data = new Dictionary<string, int>();
data.Add("abc", 123);
data.Add("def", 456);
var clone = Serializer.DeepClone(data);
Console.WriteLine(clone["abc"]);
Console.WriteLine(clone["def"]);
As will BinaryFormatter
:
using (MemoryStream ms = new MemoryStream())
{
var bf = new BinaryFormatter();
bf.Serialize(ms, data);
ms.Position = 0;
clone = (Dictionary<string, int>) bf.Deserialize(ms);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With