The issue you're seeing is down to the change from using JSON.NET
as the default serializer in ASP.NET Core 2.x to using System.Text.Json
in newer versions. With JSON.NET
these callbacks can be used, but with System.Text.Json
they aren't part of the serialization process.
One solution is to add the appropriate NuGet package and continue using JSON.NET (see this question). Alternatively, Microsoft have produced a migration documentation page for handling the change from JSON.NET to System.Text.Json.
The documentation explains that using the callbacks with System.Text.Json requires writing a custom converter:
In System.Text.Json
, you can simulate callbacks by writing a custom converter. The following example shows a custom converter for a POCO. The converter includes code that displays a message at each point that corresponds to a Newtonsoft.Json
callback.
The following sample code is provided:
public class WeatherForecastCallbacksConverter : JsonConverter<WeatherForecast>
{
public override WeatherForecast Read(
ref Utf8JsonReader reader,
Type type,
JsonSerializerOptions options)
{
// Place "before" code here (OnDeserializing),
// but note that there is no access here to the POCO instance.
Console.WriteLine("OnDeserializing");
// Don't pass in options when recursively calling Deserialize.
WeatherForecast forecast = JsonSerializer.Deserialize<WeatherForecast>(ref reader);
// Place "after" code here (OnDeserialized)
Console.WriteLine("OnDeserialized");
return forecast;
}
public override void Write(
Utf8JsonWriter writer,
WeatherForecast forecast, JsonSerializerOptions options)
{
// Place "before" code here (OnSerializing)
Console.WriteLine("OnSerializing");
// Don't pass in options when recursively calling Serialize.
JsonSerializer.Serialize(writer, forecast);
// Place "after" code here (OnSerialized)
Console.WriteLine("OnSerialized");
}
}
You can then add extra serialization code in here to handle your use case. Note that this will either need to be registered on the class itself using the [JsonConverter(type)]
attribute, or by registering it with the serializer's Converters collection.