How to troubleshoot KeyNotFoundException

Not So Sharp picture Not So Sharp · Oct 23, 2012 · Viewed 13k times · Source

I am using the following to deserialize a JSON string into my own class:

JavaScriptSerializer serializer = new JavaScriptSerializer();
Dictionary<string, object> x = (Dictionary<string, object>)serializer.DeserializeObject(json);
MyJsonStruct data = serializer.Deserialize<MyJsonStruct>(x["d"].ToString());

But as soon as the JavaScriptSerializer.Deserialize() method is called, an exception is thrown:

A first chance exception of type 'System.Collections.Generic.KeyNotFoundException' occurred in mscorlib.dll
System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
   at System.Collections.Generic.Dictionary`2.get_Item(TKey key)

Is there a way to find out which key triggered the exception?

A general technique (or recipe) for troubleshooting this type of exception would be most appreciated.

Update: If I remove the [d], I receive the following:

A first chance exception of type 'System.ArgumentException' occurred in System.Web.Extensions.dll
System.ArgumentException: Invalid JSON primitive: System.Collections.Generic.Dictionary.
   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()
   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)
   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)

But again, I am looking for a general technique more than just solving this particular instance.

Answer

tmesser picture tmesser · Oct 23, 2012

Drop a break point on the Deserialize statement, then use the Immediate Window to type in x["d"].ToString(). This will tell you what that evaluates to, which will equate to the key you are attempting to deserialize.

If you get an error while evaluating that, then your x dictionary does not have "d" as a key, which is another thing you can check.

EDIT: I don't think Daniel was suggesting you remove the ["d"] completely. If you do that, you are passing Deserialize a dictionary when it's pretty clearly expecting a string. This type mismatch is what causes the new error you see. Instead, Daniel is suggesting that the dictionary you have doesn't include "d" as a valid key. Which it may or may not, I'm not sure.