CastException when serializing derived class with System.Text.Json

huangapple go评论100阅读模式
英文:

CastException when serializing derived class with System.Text.Json

问题

我有一个简单的CLI应用程序,根据args获取不同的数据,然后使用System.Text.Json进行JSON序列化。

我遇到的问题是,在序列化派生类(例如,在这种情况下是List<DerivedImage>)时,如何使用基类的自定义转换器(例如ImageConverter)来解决这个问题?

public static int Main(string[] args)
{
  object data = "images ls" switch
  {
    "images ls" => new List<DerivedImage>() { new DerivedImage() },
    // ... 其他情况 ...
  };

  var options = new JsonSerializerOptions()
  {
    Converters = { new ImageConverter() }
  };

  var stringified = JsonSerializer.Serialize(data, options);
  // ^ 这里出错了!
  // 异常消息:
  // System.InvalidCastException: 无法将类型为 'ImageConverter'
  // 的对象强制转换为类型 'JsonConverter[DerivedImage]'

  return 1;
}

public class ImageConverter : JsonConverter<Image>
{
  public override bool CanConvert(Type typeToConvert)
  {
    return typeof(Image).IsAssignableFrom(typeToConvert);
  }

  public override Image Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  {
    throw new NotImplementedException();
  }

  public override void Write(Utf8JsonWriter writer, Image value, JsonSerializerOptions options)
  {
    // 从不会执行到这里。
  }
}

public abstract class Image { }

public class DerivedImage : Image { }

在上面的代码片段中,如何让序列化器在传递data时使用ImageConverter呢?

英文:

I've got a simple CLI app that gets some different data depending on args and then JSON serializes it using System.Text.Json.

The problem I'm running into is when serializing a derived class (ie. List<DerivedImage> in this case) with a custom converter for the base class (ie. ImageConverter).

public static int Main(string[] args)
{
  object data = "images ls" switch
  {
    "images ls" => new List<DerivedImage>() { new DerivedImage() },
    // ... etc ...
  };

  var options = new JsonSerializerOptions()
  {
    Converters = { new ImageConverter() }
  };

  var stringified = JsonSerializer.Serialize(data, options);
  // ^ THIS ERRORS!
  // Exception message:
  // System.InvalidCastException: 'Unable to cast object of type 'ImageConverter'
  // to type 'JsonConverter[DerivedImage]'

  return 1;
}

public class ImageConverter : JsonConverter<Image>
{
  public override bool CanConvert(Type typeToConvert)
  {
    return typeof(Image).IsAssignableFrom(typeToConvert);
  }

  public override Image Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  {
    throw new NotImplementedException();
  }

  public override void Write(Utf8JsonWriter writer, Image value, JsonSerializerOptions options)
  {
    // It never gets here.
  }
}

public abstract class Image { }

public class DerivedImage : Image { }

With the snippet above, how can I get the serializer to use the ImageConverter when passed data?

答案1

得分: 0

升级项目配置中的 TargetFramework.net6.net7 已解决。

英文:

Resolved by upgrading TargetFramework in the project config from .net6 to .net7.

huangapple
  • 本文由 发表于 2023年8月4日 02:26:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76830738.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定