使用JSON将JSON字符串(geocode API's google)反序列化为对象.净c#
本文关键字:JSON 反序列化 google 对象 字符串 geocode API 使用 | 更新日期: 2023-09-27 18:01:38
我使用的地理代码API的谷歌,我可以得到JSON字符串与所有日期,但当我将它转换成一个对象,它不工作,它返回任何东西,我使用JSON。. NET,我做错了什么?
在所有JSON数据中,我只想取formatted_address。json请求:http://maps.googleapis.com/maps/api/geocode/json?address=av.paulista&sensor=false%22
对不起,我的英语不好
我的主要形式:获取JSON数据(工作)
private void btnConsumir_Click(object sender, EventArgs e)
{
string address = txtAddress.Text ;
string searchCode = "http://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&sensor=false";
var JSONdata = "";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(searchCode);
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream());
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
JSONdata = streamReader.ReadToEnd();
}
lblJSON.Text = JSONdata;//its a label
这里我想获取json的formatted_address信息:
[...]
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
JSONdata = streamReader.ReadToEnd();
}
lblJSON.Text = JSONdata;//its a label
AddressObject addressObject = JsonConvert.DeserializeObject<addressObject>(JSONdata);
string result = addressObject.formatted_address;
lblJSON.Text = result;
这是我的类对象:
class AddressObject
{
public string formatted_address { get; set; }
}
非常感谢!
从api返回的结果远远多于formatted_address
。你需要对整个图进行反序列化,然后去掉你想要的。
Rootobject mapdata = JsonConvert.DeserializeObject<Rootobject>(JSONdata);
…
public class Rootobject
{
public Result[] results { get; set; }
public string status { get; set; }
}
public class Result
{
public Address_Components[] address_components { get; set; }
public string formatted_address { get; set; }
public Geometry geometry { get; set; }
public string place_id { get; set; }
public string[] types { get; set; }
}
public class Geometry
{
public Location location { get; set; }
public string location_type { get; set; }
public Viewport viewport { get; set; }
}
public class Location
{
public float lat { get; set; }
public float lng { get; set; }
}
public class Viewport
{
public Northeast northeast { get; set; }
public Southwest southwest { get; set; }
}
public class Northeast
{
public float lat { get; set; }
public float lng { get; set; }
}
public class Southwest
{
public float lat { get; set; }
public float lng { get; set; }
}
public class Address_Components
{
public string long_name { get; set; }
public string short_name { get; set; }
public string[] types { get; set; }
}