разобрать google maps геокод json ответ на объект с помощью Json.Net - PullRequest
19 голосов
/ 09 июня 2010

У меня есть БД, заполненная адресами, для которых мне нужно получить широту и длину, поэтому я хочу просмотреть их и использовать Google Geocode для обновления своей базы данных.Я застрял в том, как разобрать результат JSOn, чтобы получить то, что мне нужно:

var address = "http://maps.google.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false";
var result = new System.Net.WebClient().DownloadString(address);
GoogleGeoCodeResponse test = JsonConvert.DeserializeObject<GoogleGeoCodeResponse>(result);

Я подумал, что мог бы просто создать быстрый класс и использовать JSON.Net для десериализации результата, и это отчастиработает, но я думаю, что я дую это на мою структуру класса:

public  class GoogleGeoCodeResponse {

    public string status { get; set; }
    public geometry geometry { get; set; }

}

public class geometry {
    public string location_type { get; set; }
    public location location { get; set; }
}

public class location {
    public string lat {get;set;}
    public string lng {get;set;}
}

Вот пример того, что get возвращается из Google:

{
  "status": "OK",
  "results": [ {
    "types": [ "street_address" ],
    "formatted_address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
    "address_components": [ {
      "long_name": "1600",
      "short_name": "1600",
      "types": [ "street_number" ]
    }, {
      "long_name": "Amphitheatre Pkwy",
      "short_name": "Amphitheatre Pkwy",
      "types": [ "route" ]
    }, {
      "long_name": "Mountain View",
      "short_name": "Mountain View",
      "types": [ "locality", "political" ]
    }, {
      "long_name": "California",
      "short_name": "CA",
      "types": [ "administrative_area_level_1", "political" ]
    }, {
      "long_name": "United States",
      "short_name": "US",
      "types": [ "country", "political" ]
    }, {
      "long_name": "94043",
      "short_name": "94043",
      "types": [ "postal_code" ]
    } ],
    "geometry": {
      "location": {
        "lat": 37.4219720,
        "lng": -122.0841430
      },
      "location_type": "ROOFTOP",
      "viewport": {
        "southwest": {
          "lat": 37.4188244,
          "lng": -122.0872906
        },
        "northeast": {
          "lat": 37.4251196,
          "lng": -122.0809954
        }
      }
    }
  } ]
}

Я скучаю по простому здесь я знаю этокто-нибудь?

Ответы [ 6 ]

47 голосов
/ 02 августа 2010

Я попробовал это, сделал простой тест, и это сработало (добавили результаты и другое):

public class GoogleGeoCodeResponse
{

    public string status { get; set; }
    public results[] results { get; set; }

}

public class results
{
    public string formatted_address { get; set; }
    public geometry geometry { get; set; }
    public string[] types { get; set; }
    public address_component[] address_components { get; set; }
}

public class geometry
{
    public string location_type { get; set; }
    public location location { get; set; }
}

public class location
{
    public string lat { get; set; }
    public string lng { get; set; }
}

public class address_component
{
    public string long_name { get; set; }
    public string short_name { get; set; }
    public string[] types { get; set; }
}
20 голосов
/ 23 ноября 2011

Вы можете использовать динамический объект вместо определения объекта.

 public static dynamic GEOCodeAddress(String Address)
    {
        var address = String.Format("http://maps.google.com/maps/api/geocode/json?address={0}&sensor=false", Address.Replace(" ", "+"));
        var result = new System.Net.WebClient().DownloadString(address);
        JavaScriptSerializer jss = new JavaScriptSerializer();
        return jss.Deserialize<dynamic>(result);
    }
4 голосов
/ 22 сентября 2010

я сделал что-то подобное, см. Google Geo Kit

3 голосов
/ 10 июля 2014

Код объекта C # Я добавил несколько дополнительных классов, не уверен, что они являются новыми для API, но я подумал, что это может быть полезно для кого-то.

2 голосов
/ 12 августа 2016

Благодаря вышеприведенному JEuvin, я смог легко переключиться с XML на Json с помощью нескольких модов для кода выше (в частности, изменив значения lat и lng на десятичное или двойное), а также мне пришлось изменить address_components.types на string [] назаставить его работать на меня.Затем я немного изменил рефакторинг, чтобы те же классы можно было десериализовать из XML или Json взаимозаменяемо.

Может быть, это кому-то тоже поможет ...

using System;
using System.Xml.Serialization;

[Serializable]
[XmlType(AnonymousType = true)]
[XmlRoot(Namespace = "", IsNullable = false)]
public class GeocodeResponse
{
    public GeocodeResponse()
    {
    }

    [XmlElement("result")]

    public results[] results { get; set; }

    public string status { get; set; }
}

[XmlType(AnonymousType = true)]
public class results
{
    public results()
    {
    }

    [XmlElement("address_component")]

    public address_component[] address_components { get; set; }

    public string formatted_address { get; set; }

    public geometry geometry { get; set; }

    [XmlElement("type")]
    public string[] types { get; set; }

    public string[] postcode_localities { get; set; }

    public bool partial_match { get; set; }

    public string place_id { get; set; }
}

[XmlType(AnonymousType = true)]
public class address_component
{
    public address_component()
    {
    }

    public string long_name { get; set; }

    public string short_name { get; set; }

    [XmlElement("type")]
    public string[] types { get; set; }
}

[XmlType(AnonymousType = true)]
public class geometry
{
    public geometry()
    {
    }

    public bounds bounds { get; set; }

    public location location { get; set; }

    public string location_type { get; set; }

    public viewport viewport { get; set; }
}

[XmlType(AnonymousType = true)]
public class location
{
    public location()
    {
    }

    public double lat { get; set; }

    public double lng { get; set; }
}

[XmlType(AnonymousType = true)]
public class viewport
{
    public viewport()
    {
    }

    public northeast northeast { get; set; }

    public southwest southwest { get; set; }
}

[XmlType(AnonymousType = true)]
public class bounds
{
    public bounds()
    {
    }

    public northeast northeast { get; set; }
}

[XmlType(AnonymousType = true)]
public class northeast
{
    public northeast()
    {
    }

    public double lat { get; set; }

    public double lng { get; set; }
}

[XmlType(AnonymousType = true)]
public class southwest
{
    public southwest()
    {
    }

    public double lat { get; set; }

    public double lng { get; set; }
}

(отредактировано с добавлением postcode_localities ичастичные свойства)

0 голосов
/ 22 марта 2017

Убедитесь, что класс является Сериализуемым, разрешить обнуляемые значения

[Serializable]
[XmlType(AnonymousType = true)]
[XmlRoot(Namespace = "", IsNullable = true)]
public class GeocodeResponse
{
    public GeocodeResponse()
    {
      // can be empty or you can initiate the properties here
    }

    [XmlElement("location ")]
    [Display(Name = "location ")]
    // add json attributes as well
    public location  location { get; set; }

    public string status { get; set; }
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...