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
?