我'在使用地理编码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; }
}
非常感谢你!
答案 0 :(得分:1)
从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; }
}