Problems with Json Serialize Dictionary<Enum, Int32>

Posted by dbemerlin on Stack Overflow See other posts from Stack Overflow or by dbemerlin
Published on 2010-05-23T18:27:56Z Indexed on 2010/05/23 18:30 UTC
Read the original article Hit count: 261

Filed under:
|
|
|

Hi,
whenever i try to serialize the dictionary i get the exception:

System.ArgumentException: Type 
'System.Collections.Generic.Dictionary`2[[Foo.DictionarySerializationTest+TestEnum, Foo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'
is not supported for serialization/deserialization of a dictionary,
keys must be strings or object

My Testcase is:

public class DictionarySerializationTest
{
  private enum TestEnum { A, B, C }
  public void SerializationTest()
  {
    Dictionary<TestEnum, Int32> data = new Dictionary<TestEnum, Int32>();

    data.Add(TestEnum.A, 1);
    data.Add(TestEnum.B, 2);
    data.Add(TestEnum.C, 3);

    JavaScriptSerializer serializer = new JavaScriptSerializer();
    String result = serializer.Serialize(data);
    // Throws
  }

  public void SerializationStringTest()
  {
    Dictionary<String, Int32> data = new Dictionary<String, Int32>();

    data.Add(TestEnum.A.ToString(), 1);
    data.Add(TestEnum.B.ToString(), 2);
    data.Add(TestEnum.C.ToString(), 3);

    JavaScriptSerializer serializer = new JavaScriptSerializer();
    String result = serializer.Serialize(data);
    // Succeeds
  }

}

Of course i could use .ToString() whenever i enter something into the Dictionary but since it's used quite often in performance relevant methods i would prefer using the enum.

My only solution is using .ToString() and converting before entering the performance critical regions but that is clumsy and i would have to change my code structure just to be able to serialize the data.

Does anyone have an idea how i could serialize the dictionary as <Enum, Int32>?

I use the System.Web.Script.Serialization.JavaScriptSerializer for serialization.

© Stack Overflow or respective owner

Related posts about c#

Related posts about JSON