JavaScriptSerializer:未将对象引用设置为对象的实例

时间:2013-05-07 23:02:40

标签: c# c#-4.0 mono xamarin-studio

我在这里做错了什么?

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

2 个答案:

答案 0 :(得分:1)

我认为你的代码没有问题,除了使用count属性,并且由于代码在json被反序列化时破坏了,我建议你使用静态类型定义,只是为了缩小代码问题的变化:

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

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

答案 1 :(得分:1)

由于我无法使Dictionary<string, object>工作,我决定放弃它并使用静态类型。 BTW,this online tool对于从JSON生成C#类非常方便。