skip to content

With System.Text.Json in .NET 10, why does serializing a Document[] holding Invoice and CreditNote objects drop derived properties, and how do [JsonDerivedType] and a JsonSerializerContext fix it under Native AOT?

level: seniorimportance: should knowfreq 32%

answer

  1. declared type decides the contract
  2. discriminator written first
  3. unknown subclass throws
  4. reflection switched off by trimming
  5. contract generated at compile time

basics

~20 s

JsonSerializer uses the declared element type, so a Document[] writes only Document's members. [JsonDerivedType] on the base adds a $type discriminator and round-trips the subclasses; a JsonSerializerContext generates those contracts at compile time, which Native AOT requires.

solid answer

~40 s

System.Text.Json builds its contract from the *declared* type, so elements of a `Document[]` are written as `Document`; declaring `object` writes runtime properties but cannot read them back. Since .NET 7, `[JsonDerivedType(typeof(Invoice), "invoice")]` on the base opts the hierarchy into polymorphism: output gains `"$type":"invoice"` and deserialization creates the right subclass. By default `$type` must come first, an unregistered subclass throws `NotSupportedException`, and an unknown discriminator throws `JsonException`. Under Native AOT the reflection path is gone: `PublishAot` implies trimming, which sets `JsonSerializerIsReflectionEnabledByDefault` to false, so `JsonSerializer.Serialize(doc)` warns IL2026/IL3050 at build and throws `InvalidOperationException` at run time. A `[JsonSerializable(typeof(Document[]))]` partial `JsonSerializerContext` generates the contracts, including the registered subclasses, and you pass `ExportContext.Default.DocumentArray`.

code

csharp · 19 lines
csharp
using System.Text.Json;
using System.Text.Json.Serialization;

Document[] batch = [new Invoice { Number = "INV-1", Total = 120.50m }, new CreditNote { Number = "CN-7", Reason = "damaged" }];
string json = JsonSerializer.Serialize(batch, ExportContext.Default.DocumentArray);
Console.WriteLine(json);
// [{"$type":"invoice","Total":120.50,"Number":"INV-1"},{"$type":"credit","Reason":"damaged","Number":"CN-7"}]

foreach (Document d in JsonSerializer.Deserialize(json, ExportContext.Default.DocumentArray)!)
    Console.WriteLine(d.GetType().Name);                 // Invoice, CreditNote

[JsonDerivedType(typeof(Invoice), "invoice")]
[JsonDerivedType(typeof(CreditNote), "credit")]
public class Document { public string? Number { get; set; } }
public class Invoice : Document { public decimal Total { get; set; } }
public class CreditNote : Document { public string? Reason { get; set; } }

[JsonSerializable(typeof(Document[]))]
internal partial class ExportContext : JsonSerializerContext { }

go deeper

for a junior

Remember that System.Text.Json writes the declared type's members, and that [JsonDerivedType] on the base type adds a $type discriminator.

for a middle

Explain why object round-trips badly, where $type must sit, what an unregistered subclass or unknown discriminator does, and how a JsonSerializerContext is declared.

for a senior

Trace an AOT failure from the IL2026 and IL3050 warnings to the reflection feature switch and the InvalidOperationException, and fix it with generated metadata without losing polymorphism.

for a principal

Treat discriminator values and context coverage as versioned contract: stable names, a test per registered subtype, and a decision on how unknown subtypes are handled.

## The declared type decides the contract **System.Text.Json** serializes from a **contract** (`JsonTypeInfo`) for the type it is told about. For `JsonSerializer.Serialize(batch)` with `Document[] batch`, the element type is `Document`, so every element is written with `Document`'s properties only: an `Invoice`'s `Total` and a `CreditNote`'s `Reason` disappear without a warning. Two half-fixes are common: - **Declaring `object`** (or calling `Serialize<object>`) makes the serializer use the runtime type when writing, so the properties appear. Reading gives you nothing useful back, because the JSON carries no record of which class wrote it. - **Serializing each element separately by its runtime type** works for writing and has the same reading problem. ## Opting a hierarchy into polymorphism Since .NET 7 the serializer supports polymorphism through attributes on the **base type**: - **`[JsonDerivedType(typeof(Invoice), "invoice")]`** registers a subclass and its **type discriminator**. Each registered subclass gets its own attribute. - The discriminator is written as a metadata property, **`$type`** by default; `[JsonPolymorphic(TypeDiscriminatorPropertyName = "kind")]` renames it. - On read, the serializer uses `$type` to construct the right subclass. A payload with no discriminator deserializes as the base type. Output for the batch becomes `[{"$type":"invoice","Total":120.50,"Number":"INV-1"},{"$type":"credit","Reason":"damaged","Number":"CN-7"}]`. ## What can go wrong on the wire | Situation | Default behaviour | Setting that changes it | |---|---|---| | `$type` after other properties | `JsonException`: "The metadata property is either not supported by the type or is not the first property in the deserialized JSON object." | `JsonSerializerOptions.AllowOutOfOrderMetadataProperties = true` | | Discriminator value not registered, such as `"Invoice"` for `"invoice"` | `JsonException`: "Read unrecognized type discriminator id" | `[JsonPolymorphic(IgnoreUnrecognizedTypeDiscriminators = true)]` | | Serializing an unregistered subclass as `Document` | `NotSupportedException`: "Runtime type 'Proforma' is not supported by polymorphic type 'Document'." | `UnknownDerivedTypeHandling = FallBackToBaseType` or `FallBackToNearestAncestor` | | No discriminator in the payload | Base type is created | An abstract base throws `NotSupportedException` instead | Discriminator values are part of the wire contract: renaming a class is safe, renaming a discriminator breaks every stored document and every partner. ## Why Native AOT changes the picture The default resolver, `DefaultJsonTypeInfoResolver`, discovers members with **reflection** and can emit code at run time. A Native AOT binary has no JIT and the trimmer removes members nobody references statically, so that path cannot be trusted. Three things happen in a .NET 10 project with `PublishAot`: 1. **Build-time warnings.** Reflection-based overloads such as `JsonSerializer.Serialize<TValue>(TValue, JsonSerializerOptions)` carry `[RequiresUnreferencedCode]` and `[RequiresDynamicCode]`, so the trim and AOT analyzers report **IL2026** and **IL3050** at each call. 2. **A feature switch.** The ILLink targets set the MSBuild property `JsonSerializerIsReflectionEnabledByDefault` to `false` whenever `PublishTrimmed` is true, which `PublishAot` implies. It flows to runtimeconfig.json as `System.Text.Json.JsonSerializer.IsReflectionEnabledByDefault`. 3. **A run-time failure.** An options instance with no resolver then throws `InvalidOperationException`: "Reflection-based serialization has been disabled for this application." ## Source-generated contexts The JSON **source generator** ships with the SDK and writes the contracts as C# during compilation: 1. Declare `internal partial class ExportContext : JsonSerializerContext` and list each **root type** with `[JsonSerializable(typeof(Document[]))]`. 2. Pass the generated metadata: `JsonSerializer.Serialize(batch, ExportContext.Default.DocumentArray)`. These overloads take a `JsonTypeInfo<T>` and carry no trimming attributes. 3. Polymorphism keeps working: the generator reads `[JsonDerivedType]` and generates contracts for the registered subclasses too, so `ExportContext.Default.Invoice` exists without its own `[JsonSerializable]`. 4. Members must be accessible to the generated code: in .NET 10 the generator does not support private or protected members or accessors, or inaccessible constructors, so reflection-only customizations may need the contract customization API instead. 5. Options go on the context with `[JsonSourceGenerationOptions(JsonSerializerDefaults.Web)]` or through `ExportContext.Default.Options`. 6. A type the context does not cover fails with `NotSupportedException`: "JsonTypeInfo metadata for type 'Receipt' was not provided by TypeInfoResolver of type 'ExportContext'." Add a `[JsonSerializable]` line, or combine contexts with `JsonTypeInfoResolver.Combine` or the `TypeInfoResolverChain` list (.NET 8). The generator also has a serialization-only fast-path mode; it writes JSON without building full metadata but cannot deserialize, so most services keep the default mode. ## Reflection or generation The docs' comparison sums up the trade: the reflection path is simpler to code and supports every customization, while source generation reduces start-up time and private memory, eliminates run-time reflection and enables trim-safe size reduction. For a JIT-compiled service, reflection is acceptable; for a Native AOT exporter, generation is the only option that works, and listing the root types in one context makes that coverage reviewable.

  • A partner's system writes $type after the other properties; how do you accept its payloads?
    Set `AllowOutOfOrderMetadataProperties = true` on the options. By default the reader expects metadata properties such as `$type`, `$id` and `$ref` at the start of the object and throws `JsonException` otherwise. The runtime's own remarks warn that the setting can over-buffer large payloads during streaming deserialization.
  • A new Proforma subclass ships without a [JsonDerivedType]; what happens when it is serialized as Document?
    It throws `NotSupportedException` saying the runtime type is not supported by the polymorphic type. That is deliberate, so an unregistered type cannot leak out without a discriminator. If writing it as the base is acceptable, set `[JsonPolymorphic(UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)]`, or `FallBackToNearestAncestor` to use the closest registered ancestor.
  • How do you serve types from two libraries' source-generated contexts with one options instance?
    Set `TypeInfoResolver = JsonTypeInfoResolver.Combine(ContextA.Default, ContextB.Default)`, or since .NET 8 add contexts to `options.TypeInfoResolverChain`. Resolvers are queried in order and the first non-null contract wins, so order matters when two contexts cover the same type.

  • Serializing through a base-type array writes each object's runtime properties automatically.
  • Declaring the property as object fixes both serialization and deserialization.
  • Under Native AOT the reflection-based serializer still works, just more slowly.
  • Each derived type needs its own [JsonSerializable] line or it is written as the base type.
  • The $type discriminator may appear anywhere in the object by default.

Assumes .NET 10; attribute-based polymorphism dates from .NET 7, TypeInfoResolverChain from .NET 8, and the reflection switch is set by the .NET 10 ILLink targets whenever trimming is on.