Skip to sessions and notes

These session notes are AI-generated and may contain mistakes. Verify important details against the original recording.

System.Text.Json in .NET 11

Eirik Tsarpalis

Session · 18:22 recording · 7 min read

At a glance

  • C# 15 Discriminated Unions: direct serialization to raw values without wrappers or discriminators
  • Deserialization token-matching & ambiguity detection when cases share JSON token types (e.g. DateOrGuid)
  • Type Classifiers (JsonTypeClassifier): new converter-like abstraction for custom payload sniffing
  • Built-in structural classification for object unions based on property key sets
  • Closed classes: InferClosedTypePolymorphism = true automating $type registration via Roslyn metadata

Executive Summary

In this fast-paced, highly technical session, Eirik Tsarpalis details the major investments delivered in System.Text.Json (STJ) in .NET 11. Spanning 60 merged pull requests (17 new features/APIs, 16 source generator/AOT improvements, 8 performance optimizations, and 19 bug fixes), STJ in .NET 11 focuses on:

  1. First-Class Support for C# 15 Language Features: Comprehensive serialization and deserialization for Discriminated Unions and Closed Classes, establishing architectural boundaries between structural and nominal polymorphism.
  2. Type Classifiers (JsonTypeClassifier): A powerful new abstraction solving ambiguous union deserialization (e.g., distinguishing between DateOnly and Guid strings) via payload content-sniffing.
  3. Automated Closed-Class Polymorphism: InferClosedTypePolymorphism = true leverages compile-time Roslyn metadata to eliminate dozens of repetitive [JsonDerivedType] attributes on closed class hierarchies.
  4. Source Generator & Native AOT Parity: Eliminating reflection gaps via Unsafe Accessors for private member access ([JsonConstructor], [JsonInclude]), fixing init property data-loss bugs, supporting partial JsonSerializerContext, and introducing Generic Converter Annotations to replace legacy, non-AOT JsonConverterFactory factories.
  5. Declarative Contract Annotations: Durable type-level naming policies ([JsonNamingPolicy]) immune to runtime options drift, and class-level [JsonIgnore(Condition = WhenWritingNull)].
  6. Broader Ecosystem Roundup: JSON Lines (ndjson) serialization for ASP.NET Core streaming, out-of-the-box F# union support, open generic polymorphic hierarchies, and support for new .NET 11 numerics.

Polymorphic & Union Deserialization Pipeline

System.Text.Json enforces safe, conservative deserialization rules to prevent arbitrary polymorphic payload execution while supporting C# 15 language constructs:

flowchart TD
    subgraph Inbound ["Inbound JSON Payload"]
        JSON["JSON Data Stream / String"]
    end

    subgraph Lexer ["Utf8JsonReader Lexer"]
        Token["JsonTokenType (StartObject, String, Number, Boolean)"]
    end

    subgraph Router ["Contract & Type Resolver"]
        CheckKind{"Target C# Contract Kind"}
        
        subgraph BranchClosed ["Closed Class Hierarchy"]
            ClosedInfer{"InferClosedTypePolymorphism?"}
            DiscLookup["Read $type Discriminator Field"]
            CompileTypes["Resolve Roslyn Compile-Time Subtypes"]
        end

        subgraph BranchUnion ["C# 15 Discriminated Union"]
            TokenMatch{"Multiple Union Cases<br/>Share Same JsonTokenType?"}
            DirectBind["Direct Case Binding<br/>(e.g., Number -> int, Bool -> bool)"]
            HasClassifier{"Custom JsonTypeClassifier<br/>or Structural Configured?"}
            Sniff["Execute Content Sniffing / TryParse<br/>(e.g., DateOnly.TryParse vs Guid.TryParse)"]
            StructCheck["Match Property Key Signature<br/>(e.g., Dog.Barks vs Cat.Meows)"]
            AmbiguousError["Throw JsonException:<br/>'Ambiguous binding type'"]
        end
    end

    subgraph Materialization ["Materialization Engine"]
        UnsafeAcc["Invoke Private Constructors & Inits<br/>via UnsafeAccessors (Native AOT)"]
        Instance["Instantiated Strongly-Typed C# Object"]
    end

    JSON --> Token --> CheckKind
    CheckKind -- "Closed Class" --> ClosedInfer
    ClosedInfer -- "true" --> CompileTypes --> DiscLookup --> UnsafeAcc
    
    CheckKind -- "Union Type" --> TokenMatch
    TokenMatch -- "Unique Token Type" --> DirectBind --> UnsafeAcc
    TokenMatch -- "Shared Token Type (e.g. String)" --> HasClassifier
    HasClassifier -- "TypeClassifier" --> Sniff --> UnsafeAcc
    HasClassifier -- "Structural" --> StructCheck --> UnsafeAcc
    HasClassifier -- "None" --> AmbiguousError

    UnsafeAcc --> Instance

Key Technical Innovations

1. C# 15 Discriminated Unions in System.Text.Json

Serialization Behavior

C# 15 unions serialize cleanly into raw JSON primitives or objects without wrapper objects or synthetic metadata fields:

  • An integer case serializes as a native JSON number: 42.
  • A string case serializes as a native JSON string: "hello".
  • A POCO record case serializes as a standard JSON object: {"id": 1, "name": "widget"}.

Deserialization & Ambiguity Resolution

During deserialization, STJ inspects the inbound JsonTokenType to infer the corresponding union case. However, if multiple union cases map to the same JSON token type (e.g., union DateOrGuid = DateOnly | Guid; where both cases serialize as strings), STJ refuses to guess and throws an ambiguous binding error by default to maintain security.

Session Introduction
Session Introduction

Eirik Tsarpalis introduces System.Text.Json in .NET 11 at .NET Conf 2026.

Release Stats
Release Stats

60 pull requests merged: 17 new features, 16 AOT/source generator improvements, 8 performance enhancements.

Union Serialization
Union Serialization

C# 15 union types serializing directly to underlying primitives without wrapper objects.

Union Deserialization
Union Deserialization

Deserializing heterogeneous union payloads based on inbound JsonTokenType.

Ambiguous Union Binding Error
Ambiguous Union Binding Error

Ambiguity error when multiple union cases (DateOnly vs Guid) share the same JSON string type.

Type Classifiers (JsonTypeClassifier)

To resolve ambiguous cases, .NET 11 introduces Type Classifiers—a general-purpose abstraction allowing developers to implement custom payload sniffing:

public class DateOrGuidClassifier : JsonTypeClassifier
{
    public override Type Classify(ref Utf8JsonReader reader, JsonSerializerOptions options)
    {
        string? text = reader.GetString();
        if (DateOnly.TryParse(text, out _)) return typeof(DateOnly);
        if (Guid.TryParse(text, out _)) return typeof(Guid);
        throw new JsonException("Unsupported string format");
    }
}

Structural Classification

For unions between distinct object records (e.g., union Animal = Dog | Cat;), STJ provides built-in structural classification that inspects property keys (e.g., detecting Barks vs Meows). Eirik notes that structural classification should be used cautiously, as adding overlapping properties in future versions can introduce schema fragility.

Type Classifiers
Type Classifiers

Custom type classifiers performing content sniffing to disambiguate union cases.

Structural Classification
Structural Classification

Built-in structural classification distinguishing object union cases based on property signatures.


2. Closed Classes vs. Discriminated Unions

C# 15 introduces closed class hierarchies where all derived types must be declared within the same compilation.

Automated Polymorphism via InferClosedTypePolymorphism

In prior .NET versions, developers had to manually maintain exhaustive [JsonDerivedType] attributes on base classes. In .NET 11, STJ inspects the Roslyn compilation and automatically registers all derived types:

[JsonPolymorphic(InferClosedTypePolymorphism = true)]
public abstract closed class CartEvent;

public record ItemAdded(string Sku, int Quantity) : CartEvent;
public record CheckoutCompleted(decimal Total) : CartEvent;

Architectural Guidance: When to Use Which?

Eirik provides explicit architectural guidance for API designers:

"Always prefer closed classes over union types when modeling internal domain contracts."

  • Closed Classes: Employ explicit type discriminators ($type: "ItemAdded"), providing durable schema evolution over time. Adding new properties never breaks deserialization.
  • Union Types: Lack discriminators by definition. Relying on structural classification is brittle. Unions should be reserved for scenarios where the schema is mandated by external unowned systems (e.g., TypeScript union APIs).

Closed Classes and InferClosedTypePolymorphism
Closed Classes and InferClosedTypePolymorphism

Using InferClosedTypePolymorphism = true to eliminate repetitive [JsonDerivedType] attributes.

Unions vs Closed Classes Guidance
Unions vs Closed Classes Guidance

Architectural recommendations: prefer closed classes with discriminators for robust schema versioning.


3. Source Generator & Native AOT Improvements

Private Member Access via Unsafe Accessors

Previously, the STJ Source Generator could not bind to private constructors ([JsonConstructor]) or private fields/properties ([JsonInclude]). In .NET 11:

  • STJ emits modern C# Unsafe Accessors ([UnsafeAccessor]), allowing the source generator to access private members with zero reflection, achieving 100% Native AOT compatibility at full JIT execution speed.
  • Legacy runtimes automatically fall back to reflection-based access.

Conditional init Property Assignment

Fixed a subtle data-loss bug in prior source generators: init properties were previously reset to their default values even when completely omitted from inbound JSON payloads. In .NET 11, Unsafe Accessors ensure init properties retain their instantiated defaults when omitted.

Partial Contexts

JsonSerializerContext declarations can now be decorated with partial, allowing monolithic context registries to be cleanly partitioned across multiple source files.

Source Generator Private Members via UnsafeAccessors
Source Generator Private Members via UnsafeAccessors

Private constructors and properties supported in source generators via UnsafeAccessors.


4. Generic Converter Annotations (Replacing JsonConverterFactory)

Historically, applying a custom converter to a generic POCO (e.g., Result<T>) required authoring a complex, reflection-heavy JsonConverterFactory that routinely broke under Native AOT trimming.

In .NET 11, developers can attach open generic converter annotations directly to generic types:

[JsonConverter(typeof(ResultConverter<>))]
public record Result<T>(T? Value, bool IsSuccess);

public class ResultConverter<T> : JsonConverter<Result<T>>
{
    // Strongly typed, AOT-safe implementation
}

The source generator automatically matches the generic type arguments, eliminating reflection factories entirely.

Legacy JsonConverterFactory Boilerplate
Legacy JsonConverterFactory Boilerplate

The verbose, reflection-based JsonConverterFactory required in prior .NET versions.

Generic Converter Annotations in .NET 11
Generic Converter Annotations in .NET 11

Open generic converter annotations eliminating factory boilerplate with complete Native AOT safety.


5. Declarative Contract Attributes

  • Durable Naming Policies ([JsonNamingPolicy]): Previously, naming policies were set globally on JsonSerializerOptions at runtime, causing unexpected serialization shifts. In .NET 11, [JsonNamingPolicy(JsonKnownNamingPolicy.CamelCase)] can be declared directly on a type, with per-property overrides (KebabCaseLower).
  • Type-Level [JsonIgnore]: [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] can now be placed at the class level, eliminating the need to annotate every individual property.

Durable JsonNamingPolicy Attribute
Durable JsonNamingPolicy Attribute

Applying durable naming policies at class and property levels.

Type-Level JsonIgnore
Type-Level JsonIgnore

Class-level [JsonIgnore] skipping null values across all properties.


6. Additional Capabilities & Roundup

  • JSON Lines (ndjson) Serialization: Full serialization support complementing existing deserialization APIs, perfect for high-throughput streaming in ASP.NET Core Minimal APIs.
  • F# Discriminated Unions: Reflection serializer now supports F# unions natively out of the box.
  • Generic Polymorphic Hierarchies: Support for open generic types on [JsonDerivedType(typeof(Response<>), "response")].
  • Naming Policies & Numerics: Added PascalCase naming policy and native serialization converters for all new .NET 11 IEEE 754 decimal floats (Decimal32, Decimal64, Decimal128), BFloat16, and Complex<T>.

Feature Roundup and Documentation
Feature Roundup and Documentation

Feature roundup: JSON Lines, F# unions, .NET 11 numerics, and developer documentation.


Conclusion & Recommendations

System.Text.Json in .NET 11 solidifies its position as the high-performance, Native AOT-ready backbone of the .NET ecosystem. By delivering safe C# 15 union serialization, automated closed-class polymorphism, Unsafe Accessors for private members, and declarative naming policies, developers can build cleaner, faster, and more maintainable domain models with zero runtime reflection penalties.