Question

I have this code to get two double from jSon:

Dictionary<string, object> dict = this.GetDicFromInput();
Decimal tmpLat = (Decimal)dict["lat"];
Decimal tmpLon = (Decimal)dict["lon"];

This is GetDicFromInput:

private Dictionary<string, object> GetDicFromInput()
{
    string input = null;

    input = "{\"lon\":34.806109,\"lat\":31.9599733}";

    var json = new JavaScriptSerializer() { MaxJsonLength = int.MaxValue };
    Dictionary<string, object> dict = (Dictionary<string, object>)json.DeserializeObject(input);

    return dict;
}

And when I run it I get:

 [NullReferenceException: Object reference not set to an instance of an object.]
   BabySitter.Search.Page_Load(Object sender, EventArgs e) in \\psf\home\Documents\Visual Studio 2010\Projects\BabySitter\BabySitter\Search.aspx.cs:28
   System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
   System.Web.UI.Control.OnLoad(EventArgs e) +91
   System.Web.UI.Control.LoadRecursive() +74
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2207

This is the fail line:

Decimal tmpLat = (Decimal)dict["lat"];
Was it helpful?

Solution

Use the generic function to return the exact object type you are creating.

public T Deserialize<T>(string input)

In this case,

Dictionary<string, object> dict = json.DeserializeObject<Dictionary<string, object>(input);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top