英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论