每当我尝试序列化字典我得到例外:
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,PublicKeyToken=b77a5c561934e089]]' is not supported for serialization/deserialization of a dictionary,keys must be strings or object
我的测试是:
public class DictionarySerializationTest { public enum TestEnum { A,B,C } //tried with numbers,too: public enum TestEnum { A = 1,B = 2,C = 3 } 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 SerializationToObjectTest() { Dictionary<object,Int32> data = new Dictionary<object,Int32>(); data.Add(Enum.ToObject(typeof(TestEnum),TestEnum.A),1); data.Add(Enum.ToObject(typeof(TestEnum),TestEnum.B),2); data.Add(Enum.ToObject(typeof(TestEnum),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 } }
当然,我可以使用.ToString()每当我进入某些东西进入Dictionary时,但是由于它在性能相关的方法中经常使用,我更喜欢使用枚举.
我唯一的解决方案是在进入性能关键区域之前使用.ToString()和转换,但这是笨拙的,我必须更改我的代码结构才能够序列化数据.
有没有人有一个想法,我如何可以序列化字典作为&Enum,Int32>?
我使用System.Web.Script.Serialization.JavaScriptSerializer进行序列化.
更新:
我切换到字典< String,Int32>现在,它的工作原理,但我希望有人显示一个解决方案,因为我不喜欢使用字符串代替类型安全枚举.
解决方法
我知道这是晚了,但也许有人可以在将来使用它.您可以使用LINQ实现您需要的功能:
Dictionary<TestEnum,Int32>(); data.Add(TestEnum.A,1); data.Add(TestEnum.B,2); data.Add(TestEnum.C,3); JavaScriptSerializer serializer = new JavaScriptSerializer(); Dictionary<string,Int32> dataToSerialize = data.Keys.ToDictionary(p => p.ToString(),p => data[p]); string dataSerialized = serializer.Serialize(dataToSerialize);