1

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?

  • Does this answer your question? [Is polymorphic deserialization possible in System.Text.Json?](https://stackoverflow.com/questions/58074304/is-polymorphic-deserialization-possible-in-system-text-json). Short answer, it's not possible because it's a security hole. Allowing the payload to specify its own type information is a common source of vulnerabilities in web applications. – Dimitris Maragkos Aug 25 '22 at 09:23
  • Thanks but I'm not needing to deserialize this to C#, just to write the JSON. I've now posted a solution in the answers that I think is OK. I'm open to improvements though. – Sebastian Boutin Blomfield Aug 25 '22 at 09:47

1 Answers1

0

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.