在Google GeoCode API中从Zip获取County

时间:2018-05-14 15:02:20

标签: c# asp.net-core api-design google-geocoder

我一般都是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);

我的模型应该如何设置以匹配有效负载?如何从有效负载中获取县名?

1 个答案:

答案 0 :(得分:0)

考虑使用像Json.Net这样的框架。使用它,您可以动态地解析您的json响应,并只获取那些对您有用的部分:

var jsonResult = "some json from google api";
dynamic jsonObject = JObject.Parse(jsonResult);
var long_name = jsonObject.results[0].address_components[2].long_name;
var short_name = jsonObject.results[0].address_components[2].short_name;

如果您想使用谷歌返回的整个数据集,您可以创建一个合适的类结构(这可以通过使用json2csharp或Visual Studio Paste Special functionality等工具自动生成)反序列化你的json结果:

班级结构

public class AddressComponent
{
    public string long_name { get; set; }
    public string short_name { get; set; }
    public List<string> types { get; set; }
}

public class Northeast
{
    public double lat { get; set; }
    public double lng { get; set; }
}

public class Southwest
{
    public double lat { get; set; }
    public double lng { get; set; }
}

public class Bounds
{
    public Northeast northeast { get; set; }
    public Southwest southwest { get; set; }
}

public class Location
{
    public double lat { get; set; }
    public double lng { get; set; }
}

public class Northeast2
{
    public double lat { get; set; }
    public double lng { get; set; }
}

public class Southwest2
{
    public double lat { get; set; }
    public double lng { get; set; }
}

public class Viewport
{
    public Northeast2 northeast { get; set; }
    public Southwest2 southwest { get; set; }
}

public class Geometry
{
    public Bounds bounds { get; set; }
    public Location location { get; set; }
    public string location_type { get; set; }
    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 string place_id { get; set; }
    public List<string> postcode_localities { get; set; }
    public List<string> types { get; set; }
}

public class RootObject
{
    public List<Result> results { get; set; }
    public string status { get; set; }
}

反序列化json

var data = JsonConvert.DeserializeObject<RootObject>(jsonResult);
var long_name = data.results[0].address_components[2].long_name;
var short_name = data.results[0].address_components[2].short_name;

修改

完整示例:

string zip = "77379";
string url = "http://maps.googleapis.com/maps/api/geocode/json?address=" + zip + "&sensor=true";
var client = new HttpClient();

// 'using' forces proper cleanup after finishing the operation
using(var response = await client.GetAsync(url))
{
    if(response.IsSuccessStatusCode)
    {
        var jsonResult = await response.Content.ReadAsStringAsync();    
        dynamic jsonObject = JObject.Parse(jsonResult);

        // Consider doing some validation first to be sure that 'results' and 'address_components' contains any elements to avoid exceptions
        var long_name = jsonObject.results[0].address_components[2].long_name;
        var short_name = jsonObject.results[0].address_components[2].short_name;
    }
}