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

标签 c# json json.net

我有以下类(class)

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

我不确定如何取得进展并解决问题。

最佳答案

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

关于c# - 使用 JSON.NET 反序列化 json 时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21967563/

相关文章:

c# - ASP.NET MVC View 模型问题

c# - 如何在 C# 中模拟 java 上的对象序列化

android - 获取recyclerview位置并在点击时传递对象

java - 使用 Gson 将 LinkedTreeMap 解码为属性?

c# - Unity transform.position 无法正常工作

c# - 在编码的 UI 测试中传递命令行参数

javascript - 使用 Javascript 迭代 JSON 数据

c# - JSonConverter 如何进行泛型反序列化

c# - 如何在.net core 3.1中使用System.Text.Json获取对象内部对象的值

c# - Newtonsoft JSON.NET 和 json 键错误中的空格?