Search code examples
c#.netjsoncastingjavascriptserializer

Unable to deserialize JSON to a Dictionary<string, List<string>> using JavaScriptSerializer


I have issues deserializing JSON in my c# code using the JavaScriptSerializer library.

Here is my sample JSON:

{"A":["a","b","c","d"],"B":["a"],"C":[]}

I am using a Dictionary to hold the JSON as follows:

Dictionary<string, List<string>> myObject;

This is how I parse the JSON and cast it to my object:

myObject= (Dictionary<string, List<string>>)jsc.DeserializeObject(json);

However, at runtime, the previous line throws a Casting exception as follows

Unable to cast object of type System.Collections.Generic.Dictionary2[System.String,System.Object] to type System.Collections.Generic.Dictionary2[System.String,System.Collections.Generic.List1[System.String]]

For some reason the JavaScriptSerializer cannot recognize the JSON Array having strings as a List<string>

UPDATE

I populated my Dictionary data structure with some hardcoded strings to see what is the serialized version. It turns out to be exactly what my input JSON string is.


Solution

  • Instead of using the DeserializeObject method, use the generic Deserialize<T> method and specify Dictionary<string, List<string>> as the type argument. Then it will work correctly:

    string json = @"{""A"":[""a"",""b"",""c"",""d""],""B"":[""a""],""C"":[]}";
    
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    
    Dictionary<string, List<string>> myObject = 
        serializer.Deserialize<Dictionary<string, List<string>>>(json);
    
    foreach (KeyValuePair<string, List<string>> kvp in myObject)
    {
        Console.WriteLine(kvp.Key + ": " + string.Join(",", kvp.Value));
    }
    

    Output:

    A: a,b,c,d
    B: a
    C: