whenever i try to serialize the dictionary i get the exception:
System.ArgumentException: Type
\'System.Collections.Generic.Dictionary`2[[Foo.DictionarySerializ
I think that you are having trouble because TestEnum
is declared as a private enum
. Try marking it as a public enum
. The serializer needs to be able to find your enum via reflection in order to serialize it.
Also according to the Docs, the enums must have integer values. So you might want to write:
public enum TestEnum { A = 1, B = 2, C =3 }
Also, the docs say that this enum will just get mapped to its corresponding integer value during the serialization. So depending on what you are doing on the other end, String
s might be more expressive and easier to work with.
Use Newtonsoft (Newtonsoft.Json.dll) to serialize the Dictionary object and you'd be fine. It's a popular third party library you would have to download and include in your project as a reference.
See example below:
var _validationInfos = new Dictionary<ImportField, ValidationInfo>();
var serializedData = JsonConvert.SerializeObject(_validationInfos);
Exception says "keys must be strings or object" so try
data.Add(Enum.ToObject(typeof(TestEnum), TestEnum.A));
data.Add(Enum.ToObject(typeof(TestEnum), TestEnum.B));
data.Add(Enum.ToObject(typeof(TestEnum), TestEnum.C));
I did not test it though, just a guess.
I’ve created JavaScriptSerializer extension DeserializeDictionary- see http://geekswithblogs.net/mnf/archive/2011/06/03/javascriptserializer-extension-deserializedictionarytkey-tvalue.aspx
public static Dictionary<TKey, TValue> DeserializeDictionary<TKey, TValue>(this JavaScriptSerializer jss, string jsonText)
{
var dictWithStringKey = jss.Deserialize<Dictionary<string,TValue>>(jsonText);
var dict=dictWithStringKey.ToDictionary(de => jss.ConvertToType<TKey>(de.Key),de => de.Value);
return dict;
}
I know it's late, but maybe someone else can make use of it in the future. You can achieve what you need using LINQ:
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();
Dictionary<string, Int32> dataToSerialize = data.Keys.ToDictionary(p => p.ToString(), p => data[p]);
string dataSerialized = serializer.Serialize(dataToSerialize);