Search code examples
c#c#-4.0monoxamarin-studio

JavaScriptSerializer: Object reference not set to an instance of an object


What am I doing wrong here?

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

Solution

  • Since I could not make Dictionary<string, object> work, I've decided to drop it and use static types instead. BTW, this online tool is quite handy for generating C# classes from JSON.