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.
DeserializeObjectmethod is returning aDictionary<string,object>and you are then trying to cast it toDictionary<string, List<string>>. Even if the generic types you are closing over can be casted, it doesn't meant he generic type itself can be. For instance, you can't castIEnumerable<string>toIEnumerable<object>, even though string does inherit from object. Generics don't work that way.