How to parse response from google maps API with JSON?
c#, google-maps, json
Solution
Web Essentials has an option to 'Paste JSON as classes'. This will generate the classes you need to deserialize your JSON.
Using this option will generate the following for you:
public class Distance
{
public string text { get; set; }
public int value { get; set; }
}
public class Duration
{
public string text { get; set; }
public int value { get; set; }
}
public class Element
{
public Distance distance { get; set; }
public Duration duration { get; set; }
public string status { get; set; }
}
public class Row
{
public Element[] elements { get; set; }
}
public class Parent
{
public string[] destination_addresses { get; set; }
public string[] origin_addresses { get; set; }
public Row[] rows { get; set; }
public string status { get; set; }
}
(If you want, you can refactor the generated code to make it more readable. You will need to add Json.NET attributes to make sure that serialization is still working)
Then inside your code you can use the following line to deserialize your code:
Parent result = JsonConvert.DeserializeObject<Parent>(json);
Problem
I want to calculate the distance between points in C# with the google maps distance matrix API. I use the following code to make the request : ``` private void MapsAPICall() { //Pass request to google api with orgin and destination details HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://maps.googleapis.com/maps/api/distancematrix/json?origins=" + "51.123959,3.326682" + "&destinations=" + "51.158089,4.145267" + "&mode=Car&language=us-en&sensor=false"); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (var streamReader = new StreamReader(response.GetResponseStream())) { var result = streamReader.ReadToEnd(); if (!string.IsNullOrEmpty(result)) { Distance t = JsonConvert.DeserializeObject<Distance>(result); } } } ``` And then I want to parse the json answer into the Distance class: ``` public struct Distance { // Here I want to parse the distance and duration } ``` Here is an example of the json response I receive : http://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC&destinations=San+Francisco&mode=bicycling&language=fr-FR&sensor=false How do I parse the distance and duration into the Distance class? This is the first time I use Json so I'm not experienced with it. Ps: I have the json.net library installed.