I want to slightly tweak serialization result in a non-intrusive way.
For example, I want this class:
class A { int va; }
to be modified like this { va: value } -> { va: value * 2 }
So I tried to make a converter, but the only way I found like this:
[JsonConverter(typeof(NoConverter))]
class B : A { }
public class MyConverter : JsonConverter<A> {
public override void WriteJson(JsonWriter writer, A obj, JsonSerializer serializer) {
// serializer.Serialize(writer, obj);
// serializer.Serialize(writer, new A { va = obj.va * 2 });
serializer.Serialize(writer, new B { va = obj.va * 2 });
}
}
Is there a better way?
Problems of this way:
- Every class with converter enabled, must be forked and implement a copy method.
- Commented lines does not work because serializer blindly re-invoke converter and stack overflows.
- I did not find a way to avoid self recursion.
If there is a way to force invoke the default conversion, then the self recursion is avoided.
BTW:
Newtonsoft samples on converter are obsolete, and tests in repo not helpful.
Thanks to this SO post's NoConverter, I have at least got a working way.
Why Json.net does not use customized IsoDateTimeConverter?
This SO is interesting, but cannot solve my problem - I need to invoke the default conversion routine, which is not a converter.
Custom JsonConverter WriteJson Does Not Alter Serialization of Sub-properties