A 属性 反序列化后是 "Unable to cast type..."

A property is "Unable to cast type..." after deserialization

我有一个 CalculationModel 类型的对象,我将其序列化如下:

GenerateTextFileNoBend(path, modelNoBend); // from Main()

private static void GenerateTextFileNoBend(string path, CalculationModel model)
{
   if (!File.Exists(path)) {
      using (var file = File.CreateText(path + "noBend.txt")) {
         var json = JsonConvert.SerializeObject(model, Formatting.Indented);
         file.Write(json);
      }
   }
}

之后,我将其反序列化并将其属性与之前的对象进行比较(modelNoBend)。

var jsonText = File.ReadAllText(@"D:13\noBend.txt");
CalculationModel model = JsonConvert.DeserializeObject<CalculationModel>(jsonText);

这个想法是,在调试时,在访问 model 的 属性 Element 之后,它说

Message = "Unable to cast object of type 'Connectivity.DataModel.Longs.Element' to type 'Calculations.Common.Models.Element'."

此时类型可能无关紧要。然而,这个想法是原来的modelNoBend具有Element属性的完整功能,但是在序列化和反序列化之后,属性不再可用。

可能是什么原因?

可能值得注意的是,我很抱歉没有提供完全可重现的代码,但如果你能至少在概念方面为我提供一些可能发生的事情的帮助,我将非常高兴。

编辑基于@Nsevens

我在序列化时修改了如下代码:

  private static void GenerateTextFileNoBend(string path, CalculationModel model)
  {
     if (!File.Exists(path)) {
        using (var file = File.CreateText(path + "noBend.txt")) {
           var json = JsonConvert.SerializeObject(model, Formatting.Indented, new JsonSerializerSettings {
              TypeNameHandling = TypeNameHandling.All
           });
           file.Write(json);
        }
     }
  }

反序列化时:

CalculationModel model = JsonConvert.DeserializeObject<CalculationModel>(jsonText, new JsonSerializerSettings {
   TypeNameHandling = TypeNameHandling.All
});

我在上面的行中收到以下错误:

Newtonsoft.Json.JsonSerializationException: 'Cannot create and populate list type System.Linq.Enumerable+SelectEnumerableIterator2[Connectivity.DataModel.Generics.Connector1[System.UInt64],Calculations.Common.Models.Connector]. Path 'Elements.$values[0].Connectors.$values', line 10, position 22.'

序列化和反序列化应该是这样设置的:

TypeNameHandling = TypeNameHandling.Objects