When Iāve tried to deserialize dictionary whis strongly typed(and not string) keys, Iāve got an exception similar to the following
Type āSystem.Collections.Generic.Dictionary`2[[System.Drawing.KnownColor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]ā is not supported for serialization/deserialization of a dictionary, keys must be strings or objects.
// Type Dictionary`2 is not supported for serialization/deserialization of a dictionary, keys must be strings or objects.
Ā
To workaround the limitation, Iāve created an extension, similar to what was used for serialization inĀ
http://dukelupus.wordpress.com/2011/05/04/asp-net-mvc-json-and-a-generic-dictionary/
static class DictionaryExtensions { 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; } Ā /// ///From //http://dukelupus.wordpress.com/2011/05/04/asp-net-mvc-json-and-a-generic-dictionary/ /// public static Dictionary<string, object> ToJsonDictionary<TKey, TValue>(this Dictionary<TKey, TValue> input) { var output = new Dictionary<string, object>(input.Count); foreach (KeyValuePair<TKey, TValue> pair in input) output.Add(pair.Key.ToString(), pair.Value); return output; } Ā }
The example code to test is the following.
Note that you can use single quotes in json data, declared within a string. In this case you will not needĀ to escape double-quotes(ā)
using System.Web.Script.Serialization; using System.Drawing;//http://msdn.microsoft.com/en-us/library/system.drawing.knowncolor.aspx void Main() { //http://procbits.com/2011/04/21/quick-json-serializationdeserialization-in-c/ Ā Ā string jsonText=@"{ 'Yellow':2, 'Green': 1, 'Red': 3} "; var jss = new JavaScriptSerializer(); var dictEnum = jss.DeserializeDictionary<KnownColor,int>(jsonText); Console.WriteLine(jss.Serialize(dictEnum.ToJsonDictionary())); Console.WriteLine(dictEnum[KnownColor.Yellow]); Ā }
Ā Related links:
Json.NET (thanks to Guilherme Cardoso )
Ā
MSDN Stand-Alone JSON Serialization
The ASP.NET AJAX Serialization Process ā CodeProject
MSDN DeserializeObject
MSDN JavaScriptSerializer.ConvertToType<T> Method (Object)
MSDN JavaScriptConverter
MSDN SimpleTypeResolver Class (System.Web.Script.Serialization)
Ā
Ā