gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:49:38 25 4
gpt4 key购买 nike

我有以下类(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com