【问题标题】:Could Not Evaluate Expression on deserialization of JSON无法评估关于 JSON 反序列化的表达式
【发布时间】: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


【解决方案1】:

似乎可行的是在调试模式下重建,然后在发布模式下重建,然后再次在调试模式下重建。 我不明白为什么这个 hack 有效,但已经足够好了。

【讨论】:

  • 也许您已经成功地引用了一个 dll,即构建您的一个项目的输出,而不是添加对该项目的引用?即,您没有添加对项目 X 的​​引用,而是添加了对 X\bin\Release\X.dll 的引用?
猜你喜欢
  • 2018-11-14
  • 2017-02-09
  • 1970-01-01
  • 2023-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多