Карты Azure Маршрут / маршрут REST API Response - PullRequest
0 голосов
/ 13 ноября 2018

Я использую WebClient для доступа к API-интерфейсу Azure Direction / Route REST. Запрос завершается, но я не знаю, как обработать ответ. Код:

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

Как десериализовать ответ json, чтобы я мог легко получить доступ к полям и свойствам?

1 Ответ

0 голосов
/ 13 ноября 2018

Создание строго типизированной модели для ожидаемого ответа.

Допустим, например, что мы используем один из примеров ответов

{
  "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"
        }
      ]
    }
  ]
}

используя любой из множества онлайн инструментов, вы можете сгенерировать объектную модель

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

Вы бы десериализовали в строго типизированную модель

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

Вместо этого вы также можете использовать System.Net.Http.HttpClient, чтобы использовать коды состояния HTTP в случае неправильных запросов

Например

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

будет отображаться в

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

и используется как

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

Обратите внимание, однако

HttpClient предназначен для однократного создания экземпляра и повторного использования в течение всей жизни приложения. Создание класса HttpClient для каждого запроса приведет к исчерпанию количества розеток, доступных при больших нагрузках. Это приведет к SocketException ошибкам.

...