How do I avoid exposing a type discriminator when serializing a class that has opted into polymorphic deserialization?
I'm using System.Text.Json's JsonDerivedType
attributes to do polymorphic deserialization. So I need to specify typeDiscriminator
on the attribute, or else deserialization won't read incoming $type
fields on the JSON. But when I serialize those same classes, I don't want System.Text.Json to automatically add $type
(exposing implmentation details, etc.).
Example
[JsonDerivedType(typeof(Derived1), typeDiscriminator: "Derived1")]
[JsonDerivedType(typeof(Derived2), typeDiscriminator: "Derived2")]
public record BaseType(int Id);
public record Derived1(int Id, string Name) : BaseType(Id);
public record Derived2(int Id, bool IsActive) : BaseType(Id);
When serializing:
var values = new List<BaseType>
{
new Derived1(123, "Foo"),
new Derived2(456, true)
};
JsonSerializer.Serialize(values);
Actual output:
[
{ "$type": "Derived1", "Id": 123, "Name": "Foo" },
{ "$type": "Derived2", "Id": 456, "IsActive": true }
]
How do I avoid $type
being written?
Desired output:
[
{ "Id": 123, "Name": "Foo" },
{ "Id": 456, "IsActive": true }
]
Again, I know I could exclude typeDiscriminator
from the attribute, but then deserialization would not work.