Skip to content

Why can't a dictionary be serialized? #72176

Answered by heathbm
zms9110750 asked this question in Q&A
Discussion options

You must be logged in to vote

This has been the case for a long time as far as I can tell, check out some links below where people have been working around this issue since the early .NET days.

As for serialization, it is possible, it is just not as straight forward as JSON serialization, there are quite a few ways to do this, here are a few:

Option 1:

using System.Xml.Linq;

var dictionary = new Dictionary<string, int>
{
    { "text1", 111 },
    { "text2", 222 },
    { "text3", 333 }
};

XElement el = new XElement("Root",
    dictionary.Select(kv => new XElement(kv.Key, kv.Value)));

Console.WriteLine(el);

Result:

<Root>
  <text1>111</text1>
  <text2>222</text2>
  <text3>333</text3>
</Root>

Option 2:

using System.Xml.L…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@zms9110750
Comment options

@heathbm
Comment options

Answer selected by zms9110750
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
2 participants