System.Text.Json can deserialize JSON into derived or abstract types, and this post shows both routes: [JsonPolymorphic] with [JsonDerivedType], and a custom JsonConverter with a type map for payloads whose discriminator is not $type.
Key points
- [JsonPolymorphic] plus [JsonDerivedType] on the base type maps discriminator values such as "circle" to concrete subtypes.
- $type is the default discriminator name; TypeDiscriminatorPropertyName changes it to something like kind.
- The discriminator only appears on output when the declared type is the base type, e.g. Serialize<Shape>().
- Unregistered derived types throw unless UnknownDerivedTypeHandling is configured on the base type.
- AllowOutOfOrderMetadataProperties, added in .NET 9, accepts a discriminator that is not the first JSON property.
- A custom JsonConverter with a type map handles payloads such as the Space API's className, where $type is absent.
Real-world use
- A strongly typed SDK for the JetBrains Space HTTP API, whose metadata describes types with className values like HA_Type.Primitive
- Third-party DTOs you cannot annotate, where polymorphism options come from a DefaultJsonTypeInfoResolver modifier
- APIs that place the type discriminator after other properties and need AllowOutOfOrderMetadataProperties
- Reading type information from a payload you do not fully trust, where a type map limits which types may be instantiated
This summary was generated by the agent from the original post on Maarten Balliauw. The full text and all rights belong to its author and publisher. Go to original