【问题标题】:Get County from Zip in Google GeoCode API从 Google GeoCode API 中的 Zip 获取县
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 也许这是一个愚蠢的问题,但我如何将 json 对象返回到字符串?我不确定如何在上面的解释中分配 jsonResult
    • var 结果 = address.results;动态 jsonObject = JObject.Parse(result);休息,你可以按照上面的建议做
    • @RaviMathpal 使用JObject.Parse(result) 会导致错误,我相信因为结果是List&lt;&gt;
    • @croxy 感谢您的更新。已超出查询计数,因此我无法测试代码,直到我回到周一拥有它的客户端机器
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    相关资源
    最近更新 更多