Azure Maps Route/Directions REST API Response

Viewed 757

I am using a WebClient to access the Azure Direction/Route REST API. The request is completing but I do not know how to handle the response.The code:

string routeDetails = sb.ToString();
string url = $"https://atlas.microsoft.com/route/directions/json?sbscription-key={mapKey}&api-version=1.0&query={routeDetails}&{departAt}&{travelMode}&{routeType}&{trafic}";

WebClient req = new WebClient();
string res = await req.DownloadStringTaskAsync(url);
object obj = JsonConvert.DeserializeObject(res);

How do I deserialise the json response so that I can easly gain access to the fields and properties?

1 Answers

Create a strongly typed model for the expected response.

Lets say for example we use one of the sample responses

{
  "formatVersion": "0.0.12",
  "copyright": "Copyright 2017 TomTom International BV. All rights reserved. This navigation data is the proprietary copyright of TomTom International BV and may be used only in accordance with the terms of a fully executed license agreement entered into between TomTom International BV, or an authorised reseller and yourself. If you have not entered into such a license agreement you are not authorised to use this data in any manner and should immediately return it to TomTom International BV.",
  "privacy": "TomTom keeps information that tells us how and when you use our services. This includes information about the device you are using and the information we receive while you use the service, such as locations, routes, destinations and search queries. TomTom is unable to identify you based on the information it collects, and will not try to. TomTom uses the information for technical diagnostics, to detect fraud and abuse, to create usage reports, and to improve its services. The information is kept only for these purposes and for a limited period of time, after which it is destroyed. TomTom applies security methods based on industry standards to protect the information against unauthorised access. TomTom will not give anyone else access to the information or use it for any other purpose, unless explicitly and lawfully ordered to do so following due legal process. You can find out more at http://tomtom.com/privacy. You can contact TomTom by going to http://tomtom.com/support.",
  "routes": [
    {
      "summary": {
        "lengthInMeters": 1147,
        "travelTimeInSeconds": 162,
        "trafficDelayInSeconds": 0,
        "departureTime": "2017-09-07T16:56:58+00:00",
        "arrivalTime": "2017-09-07T16:59:40+00:00"
      },
      "legs": [
        {
          "summary": {
            "lengthInMeters": 1147,
            "travelTimeInSeconds": 162,
            "trafficDelayInSeconds": 0,
            "departureTime": "2017-09-07T16:56:58+00:00",
            "arrivalTime": "2017-09-07T16:59:40+00:00"
          },
          "points": [
            {
              "latitude": 52.50931,
              "longitude": 13.42937
            },
            {
              "latitude": 52.50904,
              "longitude": 13.42912
            },
            {
              "latitude": 52.50894,
              "longitude": 13.42904
            },
            {
              "latitude": 52.50867,
              "longitude": 13.42879
            },
            {
              "latitude": 52.5084,
              "longitude": 13.42857
            },
            {
              "latitude": 52.50791,
              "longitude": 13.42824
            },
            {
              "latitude": 52.50757,
              "longitude": 13.42772
            },
            {
              "latitude": 52.50735,
              "longitude": 13.42823
            },
            {
              "latitude": 52.5073,
              "longitude": 13.42836
            },
            {
              "latitude": 52.50573,
              "longitude": 13.43194
            },
            {
              "latitude": 52.50512,
              "longitude": 13.43336
            },
            {
              "latitude": 52.50464,
              "longitude": 13.43451
            },
            {
              "latitude": 52.5045,
              "longitude": 13.43481
            },
            {
              "latitude": 52.50443,
              "longitude": 13.43498
            },
            {
              "latitude": 52.50343,
              "longitude": 13.43737
            },
            {
              "latitude": 52.50274,
              "longitude": 13.43872
            }
          ]
        }
      ],
      "sections": [
        {
          "startPointIndex": 0,
          "endPointIndex": 15,
          "sectionType": "TRAVEL_MODE",
          "travelMode": "car"
        }
      ]
    }
  ]
}

using any one of the many tool online you can generate the object model

public partial class RouteDirectionsResponse
{
    [JsonProperty("formatVersion")]
    public string FormatVersion { get; set; }

    [JsonProperty("copyright")]
    public string Copyright { get; set; }

    [JsonProperty("privacy")]
    public string Privacy { get; set; }

    [JsonProperty("routes")]
    public Route[] Routes { get; set; }
}

public partial class Route
{
    [JsonProperty("summary")]
    public Summary Summary { get; set; }

    [JsonProperty("legs")]
    public Leg[] Legs { get; set; }

    [JsonProperty("sections")]
    public Section[] Sections { get; set; }
}

public partial class Leg
{
    [JsonProperty("summary")]
    public Summary Summary { get; set; }

    [JsonProperty("points")]
    public Point[] Points { get; set; }
}

public partial class Point
{
    [JsonProperty("latitude")]
    public double Latitude { get; set; }

    [JsonProperty("longitude")]
    public double Longitude { get; set; }
}

public partial class Summary
{
    [JsonProperty("lengthInMeters")]
    public long LengthInMeters { get; set; }

    [JsonProperty("travelTimeInSeconds")]
    public long TravelTimeInSeconds { get; set; }

    [JsonProperty("trafficDelayInSeconds")]
    public long TrafficDelayInSeconds { get; set; }

    [JsonProperty("departureTime")]
    public DateTimeOffset DepartureTime { get; set; }

    [JsonProperty("arrivalTime")]
    public DateTimeOffset ArrivalTime { get; set; }
}

public partial class Section
{
    [JsonProperty("startPointIndex")]
    public long StartPointIndex { get; set; }

    [JsonProperty("endPointIndex")]
    public long EndPointIndex { get; set; }

    [JsonProperty("sectionType")]
    public string SectionType { get; set; }

    [JsonProperty("travelMode")]
    public string TravelMode { get; set; }
}

You would deserialize to the strongly typed model

var client = new WebClient();
string json = await client.DownloadStringTaskAsync(url);
var directions = JsonConvert.DeserializeObject<RouteDirectionsResponse>(json);

You could also use System.Net.Http.HttpClient instead to take advantage of HTTP Status codes in cases of bad requests

For example

{
  "error": {
    "code": "401 Unauthorized",
    "message": "Access denied due to invalid subscription key. Make sure to provide a valid key for an active subscription."
  }
}

would map to

public partial class ErrorResponse
{
    [JsonProperty("error")]
    public Error Error { get; set; }
}

public partial class Error
{
    [JsonProperty("code")]
    public string Code { get; set; }

    [JsonProperty("message")]
    public string Message { get; set; }
}

and used like

var client = new HttpClient();
var response = await client.GetAsync(url);
if(response.IsSuccessStatusCode)
    var directions = await response.Content.ReadAsAsync<RouteDirectionsResponse>();
else {
    //...check why request failed.
    var error = await response.Content.ReadAsAsync<ErrorResponse>();
}

Note however

HttpClient is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors.

Related