【发布时间】:2018-10-24 07:14:38
【问题描述】:
总的来说,我是 API 新手。我正在尝试学习如何使用 Google GeoCode API 从用户输入的邮政编码中获取县。我正在使用 .NET Core MVC
可以通过以下 URL 看到示例负载: http://maps.googleapis.com/maps/api/geocode/json?address=77379&sensor=true
产生有效载荷:
{
"results" : [
{
"address_components" : [
{
"long_name" : "77379",
"short_name" : "77379",
"types" : [ "postal_code" ]
},
{
"long_name" : "Spring",
"short_name" : "Spring",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Harris County",
"short_name" : "Harris County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Texas",
"short_name" : "TX",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Spring, TX 77379, USA",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 30.088189,
"lng" : -95.47364999999999
},
"southwest" : {
"lat" : 29.9871611,
"lng" : -95.5887879
}
},
"location" : {
"lat" : 30.0314279,
"lng" : -95.5302337
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 30.088189,
"lng" : -95.47364999999999
},
"southwest" : {
"lat" : 29.9871611,
"lng" : -95.5887879
}
}
},
"place_id" : "ChIJtZcGtDLNQIYRtGE9AgmSOPQ",
"postcode_localities" : [ "Klein", "Spring" ],
"types" : [ "postal_code" ]
}
],
"status" : "OK"
}
例如,我想从上面的 url JSON 结果中获取字符串“Harris County”。
在我的模型中,我有:
public class GoogleAddress
{
public List<Result> results;
}
[DataContract]
public class Result
{
[DataMember(Name = "long_name")]
public string long_name { get; set; }
[DataMember(Name = "short_name")]
public string short_name { get; set; }
[DataMember(Name = "types")]
public string types { get; set; }
}
在我的控制器中,我的方法中有以下内容:
//zip to be passed as a parameter in my method later, hardcoded here for testing
string zip = "77379";
string county = "";
var serializer = new DataContractJsonSerializer(typeof(GoogleAddress));
//example url: http://maps.googleapis.com/maps/api/geocode/json?address=77379&sensor=true
string url = "http://maps.googleapis.com/maps/api/geocode/json?address=" + zip + "&sensor=true";
var client = new HttpClient();
var streamTask = client.GetStreamAsync(url);
var address = (GoogleAddress)serializer.ReadObject(await streamTask);
var result = address.results;
//how do I get the county from the result?
return View(county);
应如何设置我的模型以匹配有效负载以及如何从有效负载中获取县名称?
【问题讨论】:
标签: c# asp.net-core api-design google-geocoder