online newtonsoft google c# json google-maps

newtonsoft - json to dto c#



analizar la respuesta de geocodificación json de google maps al objeto utilizando Json.Net (6)

Asegúrate de que la clase sea serializable, permite nullables

[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; } }

Tengo una base de datos llena de direcciones que necesito para obtener latitud y duración, así que quiero recorrerlas y usar Google Geocode para actualizar mi base de datos. Estoy atascado en cuanto a cómo analizar el resultado de JSOn para obtener lo que necesito:

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

Pensé que simplemente podría construir una clase rápida y usar JSON.Net para deserializar el resultado, y está funcionando, pero creo que lo estoy soplando en mi estructura de clase:

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

Aquí hay una muestra de lo que obtuvieron los resultados de 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 } } } } ] }

Me falta simple aquí lo sé, ¿alguien?


Código de Objeto C # Agregué algunas clases adicionales, no estoy seguro si son nuevas en la API pero pensé que esto podría ser útil para alguien.

public class GoogleGeoCodeResponse { public results[] results { get; set; } public string status { get; set; } } public class results { public address_component[] address_components { get; set; } public string formatted_address { get; set; } public geometry geometry { get; set; } public string[] types { get; set; } } public class address_component { String long_name { get; set; } String short_name { get; set; } String types { 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 location { public string lat { get; set; } public string lng { get; set; } } public class viewport { public northeast northeast { get; set; } public southwest southwest { get; set; } } public class bounds { public northeast northeast { get; set; } } public class northeast { public string lat { get; set; } public string lng { get; set; } } public class southwest { public string lat { get; set; } public string lng { get; set; } }


Gracias a JEuvin arriba, pude cambiar fácilmente de XML a Json con algunos mods al código anterior (específicamente cambiando lat y lng a decimal o doble) y también tuve que cambiar address_components.types a string [] para llegar a trabaja para mi. Luego lo reprogramé un poco para que las mismas clases puedan deserializarse de XML o Json de forma intercambiable.

Tal vez esto ayude a alguien también ...

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

(editado con la adición de las propiedades postcode_localities y partial_match)



Intenté esto, hice una prueba simple y funcionó (resultados agregados y otros):

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


Puede utilizar un objeto dinámico en lugar de definir el objeto.

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