How to eliminate KeyNotFoundException

I use the following to deserialize a JSON string into my 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 any way to find out which key raised the exception?

A common technique (or recipe) for troubleshooting this type would be most appreciated.

Update: If I delete [d] , I get 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 then again, I am looking for a common technique more than just solving this particular case.

+4
source share
2 answers

Drop the breakpoint in the Deserialize statement, then use the Immediate window to enter x["d"].ToString() . This will tell you that it evaluates, which will equal the key that you are trying to deserialize.

If you get an error while evaluating this, then your x dictionary does not have a β€œd” as a key, which is one more thing you can check.

EDIT: I don't think Daniel suggested you completely remove ["d"] . If you do this, you pass in the Deserialize dictionary when it pretty clearly expects a string. This type mismatch causes a new error. Instead, Daniel suggests that the dictionary you have does not include "d" as a valid key. What it may or may not be, I'm not sure.

+5
source

Probably on your x access to the value for d .

+1
source

Source: https://habr.com/ru/post/1441635/


All Articles