2

我有这段代码可以从 json 获得两个双倍:

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

这是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;
}

当我运行它时,我得到:

 [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

这是失败线:

Decimal tmpLat = (Decimal)dict["lat"];
4

1 回答 1

1

使用泛型函数返回您正在创建的确切对象类型。

public T Deserialize<T>(string input)

在这种情况下,

Dictionary<string, object> dict = json.DeserializeObject<Dictionary<string, object>(input);
于 2013-02-13T23:12:50.523 回答