Google 地图 API - 从 JSON 响应中读取地点详情

Google Maps API - Read place details from JSON response

好的,我终于从 Google 个地方 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" ]
         }

尝试为您的 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"));

您可以使用 json2csharp 等工具从给定的 json 中创建 class 模型。这将导致类似这样的结果:

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);

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

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