首页 > 解决方案 > 从 Google GeoCode API 中的 Zip 获取县

问题描述

一般来说,我是 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-coreapi-designgoogle-geocoder

解决方案


考虑使用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;

如果您想使用从 google 返回的整个数据集,您可以创建一个合适的类结构(这可以通过使用json2csharp或 Visual Studios Paste Special 功能等工具自动化)并反序列化您的 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;
    }
}    

推荐阅读