I'm trying to create a simple app that takes a JSON document from the Google Maps API and iterates through it, showing each leg of the route, duration, and distance.
I have gotten it to display the first of leg, but I don't know how to make the boxes repeat. Maybe a foreach loop? I'm new and I'm really not sure.
var from = origin.Text;
var to = destination.Text;
var requesturl = @"http://maps.googleapis.com/maps/api/directions/json?origin="
+ from + "&alternatives=false&units=imperial&destination="
+ to + "&sensor=false";
string content = file_get_contents(requesturl);
JObject o = JObject.Parse(content);
string distance = (string)o.SelectToken("routes[0].legs[0].distance.text");
string instructions =
(string) o.SelectToken("routes[0].legs[0].steps[0].html_instructions");
txtDistance.Text = distance;
TextBox1.Text = instructions;
You can deserialize the entire JSON response and use objects to iterate over the results. This would be much more maintainable than hardcoding or calculating string paths.
You can take a look at Google Directions C# wrapper for details
This answer: Deserialize JSON into C# dynamic object? has code for some classes that let you deserialize JSON into a dynamic C# object. Sounds like it would be perfect for your needs.
As you have an example json document, you can create related contracts with http://json2csharp.com/ . You can use your object with typed properties afterwards and easily iterate through related fields.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.