我有以下类(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;
}
我收到以下异常
我不确定如何取得进展并解决问题。
最佳答案
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;
}
关于c# - 使用 JSON.NET 反序列化 json 时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21967563/