Azure Maps路线/方向REST API响应

时间:2018-11-13 15:38:02

标签: c# azure azure-maps

我正在使用WebClient来访问Azure Direction / Route REST API。请求已完成,但我不知道如何处理响应。代码:

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 :(得分:2)

为预期的响应创建强类型模型。

比如说我们使用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"
        }
      ]
    }
  ]
}

使用众多在线工具中的任何一种,您都可以生成对象模型

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错误。