1

我在这里做错了什么?

using System.Web.Script.Serialization;

string json = "{\"numbers\":[{\"one\":\"1\"},{\"two\":\"2\"},{\"three\":\"3\"}]}";
dynamic dictionary = new JavaScriptSerializer().Deserialize<dynamic>(json);
Assert.AreEqual(3, dictionary["numbers"].Count);

System.NullReferenceException : Object reference not set to an instance of an object
  at System.Web.Script.Serialization.JavaScriptSerializer.ConvertToObject (IDictionary`2 dict, System.Type type) [0x00000] in <filename unknown>:0 
  at System.Web.Script.Serialization.JavaScriptSerializer.ConvertToType (System.Type type, System.Object obj) [0x00000] in <filename unknown>:0 
  at System.Web.Script.Serialization.JavaScriptSerializer.ConvertToList (System.Collections.ArrayList col, System.Type type) [0x00000] in <filename unknown>:0 
  at System.Web.Script.Serialization.JavaScriptSerializer.ConvertToType (System.Type type, System.Object obj) [0x00000] in <filename unknown>:0 
  at System.Web.Script.Serialization.JavaScriptSerializer.ConvertToObject (IDictionary`2 dict, System.Type type) [0x00000] in <filename unknown>:0 
  at System.Web.Script.Serialization.JavaScriptSerializer.ConvertToType (System.Type type, System.Object obj) [0x00000] in <filename unknown>:0 
  at System.Web.Script.Serialization.JavaScriptSerializer.ConvertToType[Object] (System.Object obj) [0x00000] in <filename unknown>:0 
  at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[Object] (System.String input) [0x00000] in <filename unknown>:0
4

2 回答 2

2

除了使用 count 属性外,我认为您的代码没有问题,并且由于在反序列化 json 时代码会中断,因此我建议您改用静态类型定义,以缩小问题的变化范围使用您的代码:

        string json = "{\"numbers\":[{\"one\":\"1\"},{\"two\":\"2\"},{\"three\":\"3\"}]}";
        var dictionary = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(json);

也许只是在 JavaScriptSerializer 中使用动态类型存在问题,如果 JavaScriptSerializer 确实存在问题,您可以随时向 MSFT 报告。

于 2013-05-08T00:13:57.930 回答
1

由于我无法Dictionary<string, object>工作,我决定放弃它并改用静态类型。顺便说一句,这个在线工具对于从 JSON 生成 C# 类非常方便。

于 2013-05-10T16:43:15.353 回答