Can I make .NET use the object type to JSON serialize a polymorphic class?

Viewed 37

I have this one class I'm using in an ASP app that exists in various derived forms with different fields within the data I'm trying to serialize to JSON (using System.Text.Json). I've been having a look at this article which is pretty relevant: https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-polymorphism and there's a great solution in there, just declare the field as the basic object type:

public class WeatherForecastWithPreviousAsObject
{
    public DateTimeOffset Date { get; set; }
    public int TemperatureCelsius { get; set; }
    public string? Summary { get; set; }
    public object? PreviousForecast { get; set; }
}

In this example, PreviousForecast is serialized perfectly if you use the object type as opposed to the base type PreviousForecast is derived from. I've tested this solution in my own codebase and it works great.

However, I was wondering if it's at all possible to avoid having object type fields in my data and tell the JSON serializer to treat the base class as an object type when serializing. Like if I could put an attribute on the base class saying "when trying to serialize this, convert it to object type first".

I saw you can also use custom JSON converters, but really I just want to use the built in one for the object type and save a whole load of hassle. Is this possible?

1 Answers

I've figured out a pretty decent solution to this:

using System.Text.Json;
using System.Text.Json.Serialization;

public class DataMappingJsonConverter : JsonConverter<BaseClass>
{
    public override BaseClass? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        return null;
    }

    public override void Write(Utf8JsonWriter writer, BaseClass value, JsonSerializerOptions options)
    {
        JsonSerializer.Serialize<object>(writer, value, options);
    }
}

This actually works fine, but I'll leave this open for a bit in case there's an even better solution available.

Related