Default type discriminator for some subtypes in JsonDerivedType

80 Views Asked by At

For the following types' structure

public class Person { public string Name { get; set; } }
public class Adult : Person { public string Occupation { get; set; } }
... // many more subtypes

I need to have output like this (observe __type absence for the second entry):

[{"__type":"P","Name":"AbcPerson"},{"Occupation":"","Name":"XyzPerson"}]

It was easy to achieve this with System.Web.Script.Serialization using JavaScriptTypeResolver. And now I need to achieve this with System.Text.Json. To this end I can use this attributes:

[JsonDerivedType(typeof(Person), typeDiscriminator: "P")]
[JsonDerivedType(typeof(Adult))]

Works good but in my case I have too many derived types and new are coming and I need specific discriminator only for some of them. Is it possible to add instances of JsonDerivedType only for some subtypes and fall back to some default for others?

Likely I will as well accept an answer for Newtonsoft but in this case I also need to know how to change $type to __type.

0

There are 0 best solutions below