Google Maps API-从JSON响应中读取地点详细信息

时间:2019-02-05 13:52:04

标签: c# json google-places-api

好的,我终于从Google Places API中获得了所需的响应。响应由每个地址字段分隔。但是现在,我只想检索这些字段。

例如,如何从json波纹管中检索街道号码(90)?

直到现在我的代码:

string url = @"https://maps.googleapis.com/maps/api/place/details/json?placeid=" +
                  placeId + "&language=pt-BR&key=AIzaSyDYQ6IIsukjFEQ5VEaxL2VgLf8kRLSXuBM";

var result = new WebClient().DownloadString(url);

dynamic detalhes = JsonConvert.DeserializeObject(result);

这是回应的一部分:

{
   "html_attributions" : [],
   "result" : {
      "address_components" : [
         {
            "long_name" : "Casa A",
            "short_name" : "Casa A",
            "types" : [ "subpremise" ]
         },
         {
            "long_name" : "90",
            "short_name" : "90",
            "types" : [ "street_number" ]
         },
         {
            "long_name" : "Rua Carlos",
            "short_name" : "R. Carlos",
            "types" : [ "route" ]
         },
         {
            "long_name" : "Campo Belo",
            "short_name" : "Campo Belo",
            "types" : [ "sublocality_level_1", "sublocality", "political" ]
         },
         {
            "long_name" : "São Paulo",
            "short_name" : "São Paulo",
            "types" : [ "administrative_area_level_2", "political" ]
         },
         {
            "long_name" : "São Paulo",
            "short_name" : "SP",
            "types" : [ "administrative_area_level_1", "political" ]
         },
         {
            "long_name" : "13450-050",
            "short_name" : "13450-050",
            "types" : [ "postal_code" ]
         }

2 个答案:

答案 0 :(得分:1)

尝试为JSON创建模型:

public class Response
{
    public ResponseResult Result{ get; set; }
}
public class ResponseResult
{
    public ResponseResultAddress[] Address_Components{ get; set; }
}

public class ResponseResultAddress
{
    public string Long_Name { get; set; }
    public string Short_Name { get; set; }
    public string[] Types { get; set; }
}


var data = JsonConvert.DeserializeObject<Response>(result);
var street = data.Result.Address_Components.FirstOrDefault(item => item.Long_name == "90" && item.Types.Contains("street_number"));

答案 1 :(得分:1)

您可以利用json2csharp之类的工具根据给定的json创建类模型。这将导致如下结果:

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

public class Result
{
    public List<AddressComponent> address_components { get; set; }
}

public class RootObject
{
    public List<object> html_attributions { get; set; }
    public Result result { get; set; }
}

现在,您可以使用Json.NET将给定的json字符串反序列化为类型为RootObject的对象:

var data = JsonConvert.DeserializeObject<RootObject>(result);

要查询反序列化的data对象的street_number部分,可以使用LINQ:

var streetNo = data.result.address_components.FirstOrDefault(ac => ac.types.Contains("street_number"))?.long_name;