且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

'无法将当前JSON对象(例如{" Name":" value"})反序列化为类型'system.collections.generic.list`1 ...

更新时间:2022-02-12 08:36:19

不要把所有字段都放在json必须出现在类中,并且它们是否都必须在JSON和类中命名相同?怎么还能序列化?



你在类定义中缺少字段,其中一个字段的名称与其名称相同在json数据中(这是异常发生的地方--JSON有Name,你的类有PlaceName)。
Don't all of the fields in the json have to be present in the class, AND don't they all have to be named the same in the JSON and the class? How else is it going to be able to serialize?

You're missing fields in your class definition, and one of the fields isn't named the same as what's in the json data (this is where the exception is happening - JSON has "Name", and your class has "PlaceName").


那是因为你的JSON与你的类定​​义不匹配。

尝试在线生成器(这是我使用的一个: json2csharp - 从json生成c#类 [ ^ ])你得到这个:

That's because your JSON doesn't match your class definitions.
Try an online generator (here's the one I use: json2csharp - generate c# classes from json[^] ) and you get this:
public class OutboundLeg
{
    public List<int> CarrierIds { get; set; }
    public int OriginId { get; set; }
    public int DestinationId { get; set; }
    public DateTime DepartureDate { get; set; }
}

public class Quote
{
    public int QuoteId { get; set; }
    public int MinPrice { get; set; }
    public bool Direct { get; set; }
    public OutboundLeg OutboundLeg { get; set; }
    public DateTime QuoteDateTime { get; set; }
}

public class Place
{
    public int PlaceId { get; set; }
    public string IataCode { get; set; }
    public string Name { get; set; }
    public string Type { get; set; }
    public string SkyscannerCode { get; set; }
    public string CityName { get; set; }
    public string CityId { get; set; }
    public string CountryName { get; set; }
}

public class RootObject
{
    public List<Quote> Quotes { get; set; }
    public List<Place> Places { get; set; }
}


您的Outbound Leg类是JSON中的属性,但是Quote类中的List:



Your Outbound Leg class is a property in your JSON but a List in your Quote class:

public class Quote
    {
        public int QuoteId { get; set; }
        public List<MyOutboundLeg> OutboundLeg { get; set; }
    }





应该是:





Should be:

public class Quote
    {		
        public int QuoteId { get; set; }
        public MyOutboundLeg OutboundLeg { get; set; }
    }