Dictionary deserialization issue

when i try to serialize the dictionary everything works fine. but when I deserialize it shows that the number is 0. But it works fine with a list. What happens when we deserialize a list and a dictionary?

+3
source share
2 answers

Dictionaries do not actually support serialization. This is a known issue that worries many programmers, so if you google the ".NET Serialization Dictionary", you will get a lot of results with "practical" and workarounds.

This blog post , for example, suggests that you use the KeyedCollection class instead.

+3
source

If you are using .Net 3.5, you can use the DataContractSerializer, which will serialize the dictionary. It is also faster than BinaryFormatter or XmlSerializer.

using System.Runtime.Serialization;

var dict = new Dictionary<string, string>();
dict.Add("a","a");

DataContractSerializer dcs = new DataContractSerializer(dict.GetType());
MemoryStream byteStream = new MemoryStream();
dcs.WriteObject(byteStream, dict);
byteStream.Position = 0;

var dict2 = dcs.ReadObject(byteStream);
+1
source

Source: https://habr.com/ru/post/1735396/


All Articles