使用JSON.NET反序列化json时抛出异常

时间:2014-02-23 11:24:10

标签: c# json json.net

我有以下课程

public class Airport
{
    [MaxLength(75)]
    public string Name { get; set; }

    public bool NotInUse { get; set; }

    [MaxLength(50)]
    public string City { get; set; }

    [MaxLength(50)]
    public string Country { get; set; }

    [MaxLength(2)]
    public string Iso { get; set; }

    [MaxLength(3)]
    public string Iata { get; set; }

    [MaxLength(4)]
    public string Icao { get; set; }
}

我有以下json文件 - 并非所有属性都在json

    {
  "Airports":{
  [
    {
       "Name": "Belfast International",
       "City": "Belfast",
       "Country": "United Kingdom",
       "Iso": "GB",
       "Iata": "BFS"
     },
     {
       "Name": "City of Derry",
       "City": "Derry",
       "Country": "United Kingdom",
       "Iso": "GB",
       "Iata": "LDY"

     }
    ]
  }
}

我试图用这种方法反序列化json

public IList<Airport> ReadAirportsFromJson()
{
    if (File.Exists(AirportJsonFilename))
    {
        string fileContents = File.ReadAllText(AirportJsonFilename);
        var airports = JsonConvert.DeserializeObject<List<Airport>>(fileContents);
        return airports;
    }
    return null;
}

我收到以下异常

Screenshot

我不确定如何推进并解决问题。

2 个答案:

答案 0 :(得分:2)

json无效,我建议将其更改为类似

{
  "Airports":
  [
    {
       "Name": "Belfast International",
       "City": "Belfast",
       "Country": "United Kingdom",
       "Iso": "GB",
       "Iata": "BFS"
     },
     {
       "Name": "City of Derry",
       "City": "Derry",
       "Country": "United Kingdom",
       "Iso": "GB",
       "Iata": "LDY"

     }
    ]
}

并创建一个包装类

public class AirportsWrapper
{
    public List<Airport> Airports { get; set; }
}

您可以将json反序列化为AirportsWrapper并返回Airports属性

public IList<Airport> ReadAirportsFromJson()
{
    if (File.Exists(AirportJsonFilename))
    {
        string fileContents = File.ReadAllText(AirportJsonFilename);
        var airportsWrapper = JsonConvert.DeserializeObject<AirportsWrapper>(fileContents);
        if (airportsWrapper != null)
        {
            return airportsWrapper.Airports;
        }
    }
    return null;
}

演示:https://dotnetfiddle.net/NQ8JfQ

答案 1 :(得分:0)

当你像那样传递它时,你试图将整个文件反序列化为一个机场列表。如果整个文件还包含其他包含机场列表的内容,则无法使用。您必须只获取JSON的部分实际上是机场列表,或者您必须创建一个类/类来表示整个JSON文件并反序列化。从那以后,您可以转到yourObject.Airports