JavaScriptSerializer extension DeserializeDictionary

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=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a],[System.Int32, mscorlib, Version=, 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

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 //
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;//
void Main()
    string jsonText=@"{        'Yellow':2,        'Green': 1,        'Red': 3}    ";         
        var jss = new JavaScriptSerializer();
        var dictEnum = jss.DeserializeDictionary<KnownColor,int>(jsonText);

 Related links:

Json.NET (thanks to Guilherme Cardoso )

JSON Serializers In .NET


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)


posted @ Friday, June 3, 2011 7:34 AM

Comments on this entry:

# re: JavaScriptSerializer extension DeserializeDictionary<TKey, TValue>

Left by Guilherme Cardoso at 6/3/2011 8:02 AM
For that i use JSON.NET at
Really nice ;)

Your comment:

(not displayed)


Live Comment Preview: