我正在使用以下代码将JSON字符串反序列化为自己的类:
JavaScriptSerializer serializer = new JavaScriptSerializer();
Dictionary<string, object> x = (Dictionary<string, object>)serializer.DeserializeObject(json);
MyJsonStruct data = serializer.Deserialize<MyJsonStruct>(x["d"].ToString());
但是一旦调用JavaScriptSerializer.Deserialize()
方法,就会抛出异常:
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)
有没有办法找出触发异常的关键是哪个?希望能提供一种通用的技术(或方法)来解决这种类型的异常。 更新: 如果我删除
[d]
,会收到以下消息: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)
但是,我正在寻找一种通用技术,而不仅仅是解决这个特定的实例。
'x["d"]' threw an exception of type 'System.Collections.Generic.KeyNotFoundException'
的异常。因此,看起来它是问题的源头,但是如果字典没有d
作为第一个(也是唯一的)键,我该如何处理呢? - Not So Sharp.ToString()
完全是误导性的(这就是当我试图从 一个例子 中学习时发生的事情)。同时,Dictionary<string, object> x = (Dictionary<string, object>)serializer.DeserializeObject(json);
语句也完全没有必要:我只需要将原始的json
字符串传递给Deserialize()
即可。我应该知道得更好。非常感谢。 - Not So Sharp