【问题标题】:jsonconvert.deserializeobject returns nulljsonconvert.deserializeobject 返回 null
【发布时间】:2015-10-16 11:51:13
【问题描述】:

当用户输入 2 个地址值(如城市和街道)时,我正在尝试从谷歌地图获取坐标。在反序列化来自谷歌地图 api 的 Json 字符串时遇到问题。请务必非常简单帮助我了解我所缺少的。

这是 json 字符串: http://pasted.co/d9e7c1de

我需要结果/几何/位置/纬度, 结果/几何/位置/lng信息

这是我的代码:

public class Geometry
{
    [JsonProperty("bounds")]
    public Bounds bounds { get; set; }
    [JsonProperty("location")]
    public Location location { get; set; }
    [JsonProperty("location_type")]
    public string location_type { get; set; }
    [JsonProperty("viewport")]
    public Viewport viewport { get; set; }
}

public class Result
{
    public List<AddressComponent> address_components { get; set; }
    public string formatted_address { get; set; }
    public Geometry geometry { get; set; }
    public bool partial_match { get; set; }
    public string place_id { get; set; }
    public List<string> types { get; set; }
}

protected void Button1_Click(object sender, EventArgs e)
{
    double  coordinatesX = 0;
    double coordinatesY = 0;
    string APIKEY = "****************************";
    string MyAdres = TextBox1.Text + "," + TextBox2.Text;
    string stringpath;
    stringpath = "https://maps.googleapis.com/maps/api/geocode/json?address=" + MyAdres + "&key=" + APIKEY;
    WebClient Web = new WebClient();
    string Jsonstring = Web.DownloadString(stringpath).ToString();
    Result m = JsonConvert.DeserializeObject<Result>(Jsonstring);

    coordinatesX = m.geometry.location.lat;
    coordinatesY = m.geometry.location.lng;
}

【问题讨论】:

    标签: c# json google-maps serialization


    【解决方案1】:

    您需要使用另一个顶级类来反序列化响应 试试这个:

    public class Responce
    {
        public string status{get;set;}
        public List<Result> results {get;set;}
    }
    ...
    var responce = JsonConvert.DeserializeObject<Responce>(Jsonstring);
    DoSomething(responce.results);
    

    【讨论】:

    • 这确实有效,我错过了用根类解析:)
    猜你喜欢
    • 1970-01-01
    • 2021-02-26
    • 2017-07-05
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多