2

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"];
YosiFZ
  • 7,792
  • 21
  • 114
  • 221
  • Is DeserializeObject returning null? – Lews Therin Feb 13 '13 at 22:38
  • no, it return a dictonary with the two objects – YosiFZ Feb 13 '13 at 22:44
  • Which line is line 28? – D Stanley Feb 13 '13 at 22:45
  • `Dictionary dict = (Dictionary)json.DeserializeObject(input);` - Aren't you missing the `new` keyword here? – Brian Feb 13 '13 at 22:46
  • And it return Dictionary without the new key – YosiFZ Feb 13 '13 at 22:48
  • Are you using .Net 4.0? I've just copy pasted your code to a brand new console application and it works. – Ofer Zelig Feb 13 '13 at 22:52
  • Yes i use .net 4, the weired issue is that when i run it in the debug mode it run good but when i run the same code on my iis server it fail – YosiFZ Feb 13 '13 at 22:54
  • I've came accross a similar problem that explains that you need to set your json's max length, but in your case you've already done that. So that's weird. Try printing out some debug info. For example, before the `Decimal tmpLat = (Decimal)dict["lat"];` line, try printing how many items does the dictionary hold (and if not zero then what are they), and we'll continue from there... – Ofer Zelig Feb 13 '13 at 22:59
  • Thanks for the help, i make a clean on the project and remove it from the iis and upload again and it work perfectly. thank – YosiFZ Feb 13 '13 at 23:03

1 Answers1

1

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);
Darrin Doherty
  • 840
  • 1
  • 6
  • 17