On one of my classes I would like to do some post-deserialization processing.
The naive solution is
[JsonConverter(typeof(MyClassFormatter))]
public class MyClass {
internal void PostSerialisation()
{
//do stuff
}
}
public class MyClassFormatter : JsonConverter<MyClass>
{
public override MyClass Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var result = JsonSerializer.Deserialize<MyClass>(ref reader, options);
result.PostSerialisation();
return result;
}
public override void Write(Utf8JsonWriter writer, MyClass value, JsonSerializerOptions options)
{
JsonSerializer.Serialize(writer, value, options);
}
}
This does not work, obviously, because it is recursive. As I have attached my converter to the class, when I call JsonSerializer.Serialize(...) or JsonSerializer.Deserialize my customer formatter is called and well, you can see where this is going.
Does anyone know of a way of calling JsonSerializer.Serialize or JsonSerializer.Deserialize that ignores my custom formatter and does the default serialization or deserialization?
Of course I could re-implement the serialization/deserialization code but it seems likely that there must be a more elegant solution. This must be quite a common scenario.