After checking Table of differences between Newtonsoft.Json and System.Text.Json out, Callbacks are stated as Not supported, workaround, sample:
Newtonsoft.Json lets you execute custom code at several points in the
serialization or deserialization process:
- OnDeserializing (when beginning to deserialize an object)
- OnDeserialized (when finished deserializing an object)
- OnSerializing (when beginning to serialize an object)
- OnSerialized (when finished serializing an object)
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.
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace SystemTextJsonSamples
{
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");
}
}
}
Register this custom converter by adding the converter to the
Converters collection.
If you use a custom converter that follows the preceding sample:
- The
OnDeserializing code doesn't have access to the new POCO instance. To manipulate the new POCO instance at the start of
deserialization, put that code in the POCO constructor.
- Avoid an infinite loop by registering the converter in the options object and not passing in the options object when recursively calling
Serialize or Deserialize.
For more information about custom converters that recursively call
Serialize or Deserialize, see the Required properties section earlier
in this article.