【发布时间】:2020-05-12 09:25:26
【问题描述】:
我有一个非常小的 JSON 数组对象,如下所示:
{
"VehicleConfiguration": [
{
"VehicleUniqueID": 1000,
"VehicleRegistrationPlate": "XXX5981",
"VehicleType": 1,
"VehicleGrossWeight": 3900,
"VehicleTare": 900,
"VehicleStart": "07:00",
"VehicleEnd": "17:00",
"MaxStops": 45,
}
]
}
包含有关车辆的一些信息。目前我正在尝试仅读取和反序列化一辆车。
我为 JSON 对象创建了一个类:
[JsonObject(MemberSerialization.OptIn)]
public class InputConfiguration
{
[JsonProperty(PropertyName = "VehicleConfiguration")]
public List<VehicleConfiguration> VehicleConfiguration { get; set; }
}
另一个配置类
[JsonObject(MemberSerialization.OptIn)]
public class VehicleConfiguration
{
[JsonProperty(PropertyName = "VehicleUniqueID")]
public int VehicleUniqueID { get; set; }
[JsonProperty(PropertyName = "VehicleRegistrationPlate")]
public string VehicleRegistrationPlate { get; set; }
[JsonProperty(PropertyName = "VehicleType")]
public int VehicleType { get; set; }
[JsonProperty(PropertyName = "VehicleGrossWeight")]
public int VehicleGrossWeight { get; set; }
[JsonProperty(PropertyName = "VehicleTare")]
public int VehicleTare { get; set; }
[JsonProperty(PropertyName = "VehicleStart")]
public string VehicleStart { get; set; }
[JsonProperty(PropertyName = "VehicleEnd")]
public string VehicleEnd { get; set; }
[JsonProperty(PropertyName = "MaxStops")]
public int MaxStops { get; set; }
}
但不幸的是,在通过此代码进行反序列化时
private InputConfiguration ReadConfiguration(string configPath)
{
string jsonData = File.ReadAllText(configPath);
InputConfiguration config = JsonConvert.DeserializeObject<InputConfiguration>(jsonData);
return config;
}
我收到 VehicleConfiguration 无法评估表达式错误。 我已经尝试了一切,甚至只有一个值的数组,但似乎没有什么能超过错误。 提前谢谢你。
编辑
回答@Supun de Silva 提出的问题
public DataModel ReadFile(string inputPath)
{
DataModel cache = new DataModel();
cache.Config = ReadConfiguration(@"C:\Users\generic\Desktop\config.json");
return cache;
}
该方法将缓存的数据返回给 main。
【问题讨论】:
-
刚刚试了一下,效果很好。出于好奇,
private InputConfiguration ReadConfiguration(string configPath)驻留在您的代码中的哪个位置?它在哪里被调用? -
你能创建一个minimal reproducible example,因为它看起来必须是你的代码以外的东西吗?
-
这是我重新创建的,它是被破解的代码,但仍然可以使用 github.com/supunt/temp_cs_json
-
如果可以的话,把原代码放到公开的repo里,我们可以看看。
-
看来.Net版本和newtonsoft版本可能有问题(我想不出别的),因为我将项目的所有代码转移到了一个新项目中,现在一切运行顺利.
标签: c# json deserialization