C# 在JSON中反序列化多个对象不起作用

C# 在JSON中反序列化多个对象不起作用,c#,json,C#,Json,所以我尝试使用谷歌地图API来获取两个城市之间的距离。要查看其Json格式,请点击此处: 所以我的类对象看起来是这样匹配的 public class GeocodedWaypoint { public string geocoder_status { get; set; } public string place_id { get; set; } public List<string> types { get; set; } public bool?

所以我尝试使用谷歌地图API来获取两个城市之间的距离。要查看其Json格式,请点击此处:

所以我的类对象看起来是这样匹配的

public class GeocodedWaypoint
{
    public string geocoder_status { get; set; }
    public string place_id { get; set; }
    public List<string> types { get; set; }
    public bool? partial_match { get; set; }
}

public class Northeast
{
    public double lat { get; set; }
    public double lng { get; set; }
}

public class Southwest
{
    public double lat { get; set; }
    public double lng { get; set; }
}

public class Bounds
{
    public Northeast northeast { get; set; }
    public Southwest southwest { get; set; }
}

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 EndLocation
{
    public double lat { get; set; }
    public double lng { get; set; }
}

public class StartLocation
{
    public double lat { get; set; }
    public double lng { get; set; }
}

public class Distance2
{
    public string text { get; set; }
    public int value { get; set; }
}

public class Duration2
{
    public string text { get; set; }
    public int value { get; set; }
}

public class EndLocation2
{
    public double lat { get; set; }
    public double lng { get; set; }
}

public class Polyline
{
    public string points { get; set; }
}

public class StartLocation2
{
    public double lat { get; set; }
    public double lng { get; set; }
}

public class Step
{
    public Distance2 distance { get; set; }
    public Duration2 duration { get; set; }
    public EndLocation2 end_location { get; set; }
    public string html_instructions { get; set; }
    public Polyline polyline { get; set; }
    public StartLocation2 start_location { get; set; }
    public string travel_mode { get; set; }
    public string maneuver { get; set; }
}

public class Leg
{
    public Distance distance { get; set; }
    public Duration duration { get; set; }
    public string end_address { get; set; }
    public EndLocation end_location { get; set; }
    public string start_address { get; set; }
    public StartLocation start_location { get; set; }
    public List<Step> steps { get; set; }
    public List<object> traffic_speed_entry { get; set; }
    public List<object> via_waypoint { get; set; }
}

public class OverviewPolyline
{
    public string points { get; set; }
}

public class Route
{
    public Bounds bounds { get; set; }
    public string copyrights { get; set; }
    public List<Leg> legs { get; set; }
    public OverviewPolyline overview_polyline { get; set; }
    public string summary { get; set; }
    public List<object> warnings { get; set; }
    public List<object> waypoint_order { get; set; }
}

public class RootObject
{
    public List<GeocodedWaypoint> geocoded_waypoints { get; set; }
    public List<Route> routes { get; set; }
    public string status { get; set; }
}
提前感谢

使用生成此代码

jsonString
是来自谷歌地图API的API响应

对于本例,我使用了以下API:

//若要解析此JSON数据,请添加NuGet“Newtonsoft.JSON”,然后执行以下操作:
//
//使用QuickType;
//
//var data=GettingStarted.FromJson(jsonString);
//
命名空间快速类型
{
使用制度;
Net系统;
使用System.Collections.Generic;
使用Newtonsoft.Json;
公共部分类正在启动
{
[JsonProperty(“路线”)]
公共路由[]路由{get;set;}
[JsonProperty(“地理编码的航路点”)]
公共GeocodedWaypoint[]GeocodedWaypoints{get;set;}
[JsonProperty(“状态”)]
公共字符串状态{get;set;}
}
公共部分班路线
{
[JsonProperty(“概述”多段线)]
公共多段线概览多段线{get;set;}
[JsonProperty(“版权”)]
公共字符串版权{get;set;}
[JsonProperty(“边界”)]
公共边界{get;set;}
[JsonProperty(“腿部”)]
公共分支[]分支{get;set;}
[JsonProperty(“警告”)]
公共对象[]警告{get;set;}
[JsonProperty(“摘要”)]
公共字符串摘要{get;set;}
[JsonProperty(“航路点命令”)]
公共对象[]航路点顺序{get;set;}
}
公共部分类多段线
{
[JsonProperty(“点”)]
公共字符串点{get;set;}
}
公共部分类界
{
[JsonProperty(“东北”)]
公共结束位置{get;set;}
[JsonProperty(“西南”)]
公共结束位置{get;set;}
}
公共部分类结束位置
{
[JsonProperty(“lat”)]
公共双Lat{get;set;}
[JsonProperty(“lng”)]
公共双精度{get;set;}
}
部分公开课
{
[JsonProperty(“结束位置”)]
公共结束位置结束位置{get;set;}
[JsonProperty(“期限”)]
公共距离持续时间{get;set;}
[JsonProperty(“距离”)]
公共距离距离{get;set;}
[JsonProperty(“结束地址”)]
公共字符串结束地址{get;set;}
[JsonProperty(“开始位置”)]
公共结束位置{get;set;}
[JsonProperty(“交通速度入口”)]
公共对象[]TrafficSpeedEntry{get;set;}
[JsonProperty(“起始地址”)]
公共字符串StartAddress{get;set;}
[JsonProperty(“步骤”)]
公共步骤[]步骤{get;set;}
[JsonProperty(“通过航路点”)]
公共对象[]通过航路点{get;set;}
}
公共部分类距离
{
[JsonProperty(“文本”)]
公共字符串文本{get;set;}
[JsonProperty(“价值”)]
公共长值{get;set;}
}
公共部分类步骤
{
[JsonProperty(“html_指令”)]
公共字符串HtmlInstructions{get;set;}
[JsonProperty(“期限”)]
公共距离持续时间{get;set;}
[JsonProperty(“距离”)]
公共距离距离{get;set;}
[JsonProperty(“结束位置”)]
公共结束位置结束位置{get;set;}
[JsonProperty(“多段线”)]
公共多段线多段线{get;set;}
[JsonProperty(“机动”)]
公共字符串{get;set;}
[JsonProperty(“开始位置”)]
公共结束位置{get;set;}
[JsonProperty(“旅行模式”)]
公共字符串TravelMode{get;set;}
}
公共部分类GeocodedWaypoint
{
[JsonProperty(“部分匹配”)]
公共bool?PartialMatch{get;set;}
[JsonProperty(“地理编码器状态”)]
公共字符串GeocoderStatus{get;set;}
[JsonProperty(“地点id”)]
公共字符串PlaceId{get;set;}
[JsonProperty(“类型”)]
公共字符串[]类型{get;set;}
}
公共部分类正在启动
{
公共静态gettingstartedfromJSON(字符串json)=>JsonConvert.DeserializeObject(json,Converter.Settings);
}
公共静态类序列化
{
公共静态字符串ToJson(此GettingStarted self)=>JsonConvert.SerializeObject(self,Converter.Settings);
}
公共类转换器
{
公共静态只读JsonSerializerSettings设置=新JsonSerializerSettings
{
MetadataPropertyHandling=MetadataPropertyHandling.Ignore,
DateParseHandling=DateParseHandling.None,
};
}
}

你的
json
对象里面有什么?除了没有向我们展示你的
json
对象之外,你还有一个名为
RootObject
的类,我打赌它是你应该反序列化的主要对象。我打赌你以前也这样做过。返回的响应不是
Leg
,因此
JsonConvert.DeserializeObject(json)
不起作用。看起来您的
RootObject
与响应匹配。另外,返回的JSON是snake case,我不确定,但我非常确定Newtonsoft.JSON和Microsoft的JSON反序列化程序(无法立即记住该类)默认情况下都不会将snake case映射到Pascal case。您对JSON对象调用什么?比如json响应?我还提供了一个链接,可以让您找到它,JSON2Charp有什么问题吗?我以前使用过它,如果有问题,我会在那里添加更多的代码helpful@oceanichelicopter您应该反序列化到
RootObject
。使用json2csharp的问题是,有时它会为primiti创建错误的数据类型
 static async Task<Leg> GetLegAsync(string path)
    {
        Leg leg = null;
        HttpResponseMessage response = await client.GetAsync(path);
        if (response.IsSuccessStatusCode)
        {
            var json = await response.Content.ReadAsStringAsync();
            leg = JsonConvert.DeserializeObject<Leg>(json);

        }

        return leg;
    }
 static async Task RunAsync(string pos1,string pos2)
    {
        string apiKey = "MUST_KEEP_HIDDEN!";

        client.BaseAddress = new Uri("https://maps.googleapis.com/maps/api/directions/json?origin="+pos1+"&destination="+pos2+"&key=" + apiKey);

        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        //Console.ReadLine();
        Leg leg = await GetLegAsync("https://maps.googleapis.com/maps/api/directions/json?origin=" + pos1 + "&destination=" + pos2 + "4&key=" + apiKey);

        showinfo(leg);

    }
// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
//
//    using QuickType;
//
//    var data = GettingStarted.FromJson(jsonString);
//
namespace QuickType
{
    using System;
    using System.Net;
    using System.Collections.Generic;

    using Newtonsoft.Json;

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

        [JsonProperty("geocoded_waypoints")]
        public GeocodedWaypoint[] GeocodedWaypoints { get; set; }

        [JsonProperty("status")]
        public string Status { get; set; }
    }

    public partial class Route
    {
        [JsonProperty("overview_polyline")]
        public Polyline OverviewPolyline { get; set; }

        [JsonProperty("copyrights")]
        public string Copyrights { get; set; }

        [JsonProperty("bounds")]
        public Bounds Bounds { get; set; }

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

        [JsonProperty("warnings")]
        public object[] Warnings { get; set; }

        [JsonProperty("summary")]
        public string Summary { get; set; }

        [JsonProperty("waypoint_order")]
        public object[] WaypointOrder { get; set; }
    }

    public partial class Polyline
    {
        [JsonProperty("points")]
        public string Points { get; set; }
    }

    public partial class Bounds
    {
        [JsonProperty("northeast")]
        public EndLocation Northeast { get; set; }

        [JsonProperty("southwest")]
        public EndLocation Southwest { get; set; }
    }

    public partial class EndLocation
    {
        [JsonProperty("lat")]
        public double Lat { get; set; }

        [JsonProperty("lng")]
        public double Lng { get; set; }
    }

    public partial class Leg
    {
        [JsonProperty("end_location")]
        public EndLocation EndLocation { get; set; }

        [JsonProperty("duration")]
        public Distance Duration { get; set; }

        [JsonProperty("distance")]
        public Distance Distance { get; set; }

        [JsonProperty("end_address")]
        public string EndAddress { get; set; }

        [JsonProperty("start_location")]
        public EndLocation StartLocation { get; set; }

        [JsonProperty("traffic_speed_entry")]
        public object[] TrafficSpeedEntry { get; set; }

        [JsonProperty("start_address")]
        public string StartAddress { get; set; }

        [JsonProperty("steps")]
        public Step[] Steps { get; set; }

        [JsonProperty("via_waypoint")]
        public object[] ViaWaypoint { get; set; }
    }

    public partial class Distance
    {
        [JsonProperty("text")]
        public string Text { get; set; }

        [JsonProperty("value")]
        public long Value { get; set; }
    }

    public partial class Step
    {
        [JsonProperty("html_instructions")]
        public string HtmlInstructions { get; set; }

        [JsonProperty("duration")]
        public Distance Duration { get; set; }

        [JsonProperty("distance")]
        public Distance Distance { get; set; }

        [JsonProperty("end_location")]
        public EndLocation EndLocation { get; set; }

        [JsonProperty("polyline")]
        public Polyline Polyline { get; set; }

        [JsonProperty("maneuver")]
        public string Maneuver { get; set; }

        [JsonProperty("start_location")]
        public EndLocation StartLocation { get; set; }

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

    public partial class GeocodedWaypoint
    {
        [JsonProperty("partial_match")]
        public bool? PartialMatch { get; set; }

        [JsonProperty("geocoder_status")]
        public string GeocoderStatus { get; set; }

        [JsonProperty("place_id")]
        public string PlaceId { get; set; }

        [JsonProperty("types")]
        public string[] Types { get; set; }
    }

    public partial class GettingStarted
    {
        public static GettingStarted FromJson(string json) => JsonConvert.DeserializeObject<GettingStarted>(json, Converter.Settings);
    }

    public static class Serialize
    {
        public static string ToJson(this GettingStarted self) => JsonConvert.SerializeObject(self, Converter.Settings);
    }

    public class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
        };
    }
}