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://learn.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?