Skip to content

[API Proposal]: System.Text.Json union type support #127299

Closed

Description

@eiriktsarpalis

Background and motivation

The C# compiler just introduced support for union types. Sibling proposals for closed hierarchies and closed enums are not yet available in the compiler preview, so this issue is scoped to unions only. System.Text.Json support for closed hierarchies and closed enums will be tracked separately once their compiler features land.

This issue is a sub-issue of the broader STJ union/closed-types umbrella (#125449), extracting the API surface that is relevant today.

The goal is twofold:

  1. Provide out-of-the-box serialization support for simple union types whose union cases present no structural ambiguity (e.g. union Result(int, string)).
  2. Provide a case classifier abstraction for unions whose cases are of the same type (e.g. union Pet(Cat, Dog) where both serialize as JSON objects). This abstraction is also extended to the existing polymorphic type infrastructure.

Design summary

Serialization: no discriminator

Union values serialize transparently — the wrapper produced by the C# union keyword is unpacked and the underlying case value is written using its own JSON contract. There is no envelope object, no $type field, no tagging of any kind:

union Result(int, string);

JsonSerializer.Serialize<Result>(new Result(42));      // 42
JsonSerializer.Serialize<Result>(new Result("hello")); // "hello"

This is a deliberate departure from the polymorphism support exposed via [JsonPolymorphic] / [JsonDerivedType], where derived types are written with a $type discriminator. Unions don't have a natural discriminator: any case can be picked by the union's constructors, and two distinct case constructors can produce equal values. Synthesising an artificial discriminator (e.g. the case type name) would push that arbitrary choice into the wire format and lock STJ into it forever. Users who want a tagged representation can keep using polymorphic hierarchies, or attach a custom converter.

Deserialization: first-token dispatch

Without a discriminator on the wire, the converter has to recover the case type from the JSON value itself. The chosen mechanism is to look at a single thing — the first token of the value — and pick the unique union case whose declared type is compatible with that token kind. The mapping is fixed:

JsonTokenType Compatible case types
Number numeric primitives (int, long, double, decimal, …)
String string, DateTime, DateTimeOffset, Guid, TimeSpan, Uri, char, byte[], enums
True / False bool
StartObject objects and dictionaries
StartArray arrays and collections
Null null

Selection is O(1) and does not require read-ahead. union Result(int, string) works cleanly out of the box because int is the only case compatible with Number and string is the only case compatible with String.

This approach avoids $O(n^2)$ deserialization time when handling recursive/nested union values, a potential vector for DOS attacks.

Ambiguous unions

The token-only rule is intentionally narrow, so a number of perfectly valid unions cannot be disambiguated by it:

  • union Num(int, long) — both cases are Number.
  • union When(DateTime, DateTimeOffset) — both cases are String.
  • union Pet(Cat, Dog) — both cases are StartObject.

For these unions, the metadata layer throws InvalidOperationException when deserialization is being attempted, and the source generator emits the diagnostic SYSLIB1227 so the failure surfaces at compile time. In such cases, the user is expected to attach a custom JsonTypeClassifier that decides which case applies.

Why not built-in structural matching or content sniffing?

Two natural-looking alternatives were considered and rejected as defaults:

  • Structural matching, where the converter parses the value and tries each case type until one succeeds, would in principle resolve union Pet(Cat, Dog) automatically. But it requires unbounded read-ahead, costs O(n) on every value, and silently chooses an arm when more than one case structurally matches — which is precisely the case where the user most needs an error.
  • Content sniffing for ambiguous string forms (e.g. attempting to parse "2024-05-01" as DateTime first, falling back to string) is culture-sensitive, security-sensitive, and produces results that depend on which parsers happen to accept which inputs.

Custom classifiers

Union case classification can be customized in non-trivial shapes by implementing a JsonTypeClassifier. This follows a pattern similar to authoring custom converters:

record Dog(string? Name, string? Breed);
record Cat(string? Name, int Lives);

[JsonUnion(TypeClassifier = typeof(PetClassifier))]
union Pet(Cat, Dog);

public sealed class PetClassifier : JsonTypeClassifierFactory<Pet>
{
    public override JsonTypeClassifier CreateJsonClassifier(
        JsonTypeClassifierContext context, JsonSerializerOptions options)
    {
        // The classifier delegate is being passed a pre-buffered
        // defensive copy of the underlying Utf8JsonReader.
        return static (ref Utf8JsonReader reader) =>
        {
            if (reader.TokenType is not JsonTokenType.StartObject)
            {
                return null;
            }

            while (reader.Read() && reader.TokenType is not JsonTokenType.EndObject)
            {
                Debug.Assert(reader.TokenType is JsonTokenType.PropertyName);

                if (reader.ValueTextEquals("Breed"u8)) return typeof(Dog);
                if (reader.ValueTextEquals("Lives"u8)) return typeof(Cat);

                reader.Read(); // Advance to the value of the property.
                reader.Skip(); // Skip the value.
            }

            return null;
        };
    }
}

A higher-level alternative parses the value into a JsonNode first — simpler to write, more allocation:

public sealed class JsonNodePetClassifier : JsonTypeClassifierFactory<Pet>
{
    public override JsonTypeClassifier CreateJsonClassifier(
        JsonTypeClassifierContext context, JsonSerializerOptions options)
    {
        return static (ref Utf8JsonReader reader) =>
        {
            if (JsonNode.Parse(ref reader) is JsonObject obj)
            {
                if (obj.ContainsKey("Breed")) return typeof(Dog);
                if (obj.ContainsKey("Lives")) return typeof(Cat);
            }

            return null; // No union case identified, fail deserialization.
        };
    }
}

Below is an example of implementing a multi-type classifier factory that performs precomputations:

JsonSerializerOptions options = new() { Classifiers = { new PropertyBasedClassifier() } };

public sealed class PropertyBasedClassifier : JsonTypeClassifierFactory
{
    // Multivariate factory: applies to any union type. Override CanClassify to scope it
    // to a specific set of types if needed.
    public override bool CanClassify(Type declaringType) => true;

    public override JsonTypeClassifier CreateJsonClassifier(JsonTypeClassifierContext context, JsonSerializerOptions options)
    {
        // Precompute a property-name-to-type index, happens once.
        Dictionary<string, Type> propertyIndex = new(StringComparer.OrdinalIgnoreCase);
        foreach (JsonUnionCaseInfo unionCase in context.UnionCases)
        {
            foreach (JsonPropertyInfo prop in options.GetTypeInfo(unionCase .Type).Properties)
            {
                if (prop.Name is { } name)
                {
                    propertyIndex.TryAdd(name, dt.DerivedType);
                }
            }
        }

        return (ref Utf8JsonReader reader) =>
        {
            // Deserialization hot path
            if (reader.TokenType is not JsonTokenType.StartObject)
            {
                return null;
            }

            while (reader.Read() && reader.TokenType is not JsonTokenType.EndObject)
            {
                Debug.Assert(reader.TokenType is JsonTokenType.PropertyName);

                if (propertyIndex.TryGetValue(reader.GetString()!, out Type? match))
                {
                    return match;
                }

                reader.Read();
                reader.Skip();
            }

            return null;
        };
    }
}

Null handling

C# unions accept null if and only if at least one case constructor parameter is declared nullable, and dispatch the null value to a nullable case's constructor. Any number of cases may be declared nullable — union(int?, string?, bool?, Dog?) is well-formed. By the union spec, passing null to any nullable case yields the same null-holding union value, so all such constructors are observationally equivalent on null:

union Pet(Dog?, Cat, Bird?);   // multiple nullable cases — allowed

Pet pet1 = (Dog?)null;
Pet pet2 = (Bird?)null;
Debug.Assert(pet1 == pet2);    // same canonical null union value
// Pet pet = (Cat?)null;       // would error: Cat case is not nullable

JsonUnionConverter mirrors that semantics:

  • Serialization. A null underlying case value writes JSON null. (Reachable only when the case is nullable; otherwise the union value cannot itself be null.)
  • Deserialization. When the reader is positioned on JsonTokenType.Null, the converter short-circuits — any configured JsonTypeClassifier is bypassed — and dispatches directly to a nullable case's constructor with a null argument. If no case is nullable, JsonException is thrown. When more than one case is nullable, the first declared nullable case is chosen — by spec, passing null to any nullable case yields the same null-holding union value, so the choice is semantically transparent. Custom classifier authors therefore do not need to handle the Null token, and existing classifier implementations are unaffected by per-union nullability.
  • Multiple nullable cases. Explicitly supported and not rejected. The deserializer always picks the first declared nullable case at the Null token; round-trip equality is preserved because all nullable case constructors collapse to the same null union per the spec.
  • Source-generated metadata. Per-case nullability is carried on JsonUnionCaseInfo.IsNullable (see API additions below). The source generator emits it from the constructor parameter's nullability annotation and inserts a null-dispatch prologue in the generated UnionConstructor so the right case constructor is invoked for null without re-walking case metadata at runtime.

Schema generation

JsonSchemaExporter emits an anyOf schema composed from JsonTypeInfo.UnionCases, with shared JsonSchemaType values hoisted to the parent. For example, union(string, int) produces:

{
  "anyOf": [
    { "type": "string" },
    { "type": "integer" }
  ]
}

Schema output is classifier-invariant — the exporter does not invoke TypeClassifier, so swapping or removing a custom classifier does not change the generated schema. This mirrors polymorphic hierarchies, whose schema depends only on the registered DerivedTypes list and not on runtime discriminator resolution.

Each union case whose JsonUnionCaseInfo.IsNullable is true OR-ins JsonSchemaType.Null into its sub-schema. For union(string, int?):

{
  "anyOf": [
    { "type": "string" },
    { "type": ["integer", "null"] }
  ]
}

Source-generated metadata

For each compiler union, the source generator emits a CreateUnionInfo<T>(...) call populating JsonUnionInfoValues<T>. The case list is sorted most-derived-first using the topological-sort helpers shared with the rest of the source generator, so that the switch-based dispatch in the generated constructor and deconstructor never selects a base case before a derived one. Per-case nullability is recorded on JsonUnionCaseInfo.IsNullable and threads through both directions of the bridge:

class Dog;
class Lab : Dog;
class Bird;

union Pet(Dog, Lab, Bird?);

Generated metadata:

var unionInfo = new JsonUnionInfoValues<Pet>
{
    UnionCases = new JsonUnionCaseInfo[]
    {
        new JsonUnionCaseInfo(typeof(Lab)),                          // most-derived first
        new JsonUnionCaseInfo(typeof(Dog)),
        new JsonUnionCaseInfo(typeof(Bird)) { IsNullable = true },  // nullable case
    },
    UnionConstructor = static (Type _, object? value) => value switch
    {
        Lab caseValue0 => new Pet(caseValue0),
        Dog caseValue1 => new Pet(caseValue1),
        Bird caseValue2 => new Pet(caseValue2),
        null => new Pet((Bird?)null), // null dispatches to the nullable case
    },
    UnionDeconstructor = static (Pet value) => value switch
    {
        Lab caseValue0 => (typeof(Lab), caseValue0),
        Dog caseValue1 => (typeof(Dog), caseValue1),
        Bird caseValue2 => (typeof(Bird), caseValue2),
        null => (typeof(Bird), null), // null reports the nullable case type
    },
};

The Type parameter of UnionConstructor is unused in the generated form because pattern matching on value is sufficient to pick the right union case constructor; it is preserved on the public delegate for hand-written contracts that may want to dispatch on case type explicitly.

API proposal

namespace System.Text.Json.Serialization;

// Classifier abstraction

public delegate Type? JsonTypeClassifier(ref Utf8JsonReader reader);

public sealed class JsonTypeClassifierContext
{
    public Type DeclaringType { get; }
    public IReadOnlyList<JsonUnionCaseInfo> UnionCases { get; }
    public IReadOnlyList<JsonDerivedType> DerivedTypes { get; }
    public string? TypeDiscriminatorPropertyName { get; }
}

public abstract class JsonTypeClassifierFactory
{
    public abstract bool CanClassify(Type declaringType);
    public abstract JsonTypeClassifier CreateJsonClassifier(
        JsonTypeClassifierContext context, JsonSerializerOptions options);
}

public abstract class JsonTypeClassifierFactory<T> : JsonTypeClassifierFactory
{
    public sealed override bool CanClassify(Type declaringType) => declaringType == typeof(T);
}

// New options-level surface

public sealed partial class JsonSerializerOptions
{
    public IList<JsonTypeClassifierFactory> Classifiers { get; }
}

public sealed partial class JsonSourceGenerationOptionsAttribute
{
    public Type[]? Classifiers { get; set; }
}

// New attribute APIs

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)]
public sealed class JsonUnionAttribute : JsonAttribute
{
    [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]
    public Type? TypeClassifier { get; set; }
}

public sealed partial class JsonPolymorphicAttribute
{
    [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]
    public Type? TypeClassifier { get; set; }
}
namespace System.Text.Json.Serialization.Metadata;

// Contract customization surface for union types

public sealed class JsonUnionCaseInfo
{
    public JsonUnionCaseInfo(Type caseType);
    public Type CaseType { get; }
    public bool IsNullable { get; init; }
}

public enum JsonTypeInfoKind
{
    /** Existing values **/
    // None = 0,
    // Object = 1,
    // Enumerable = 2,
    // Dictionary = 3,

    Union = 4,
}

public abstract partial class JsonTypeInfo
{
    public JsonTypeClassifier? TypeClassifier { get; set; }
    public IList<JsonUnionCaseInfo>? UnionCases { get; set; }
    public Func<Type, object?, object>? UnionConstructor { get; set; }
    public Func<object, (Type? CaseType, object? CaseValue)>? UnionDeconstructor { get; set; }
}

public sealed partial class JsonTypeInfo<T>
{
    public new Func<Type, object?, T>? UnionConstructor { get; set; }
    public new Func<T, (Type? CaseType, object? CaseValue)>? UnionDeconstructor { get; set; }
}

We also need to expose a few APIs specifically for consumption by the source generator:

[EditorBrowsable(EditorBrowsableState.Never)]
public sealed class JsonUnionInfoValues<T>
{
    public IList<JsonUnionCaseInfo>? UnionCases { get; init; }
    public Func<Type, object?, T>? UnionConstructor { get; init; }
    public JsonTypeClassifier? TypeClassifier { get; init; }
    public Func<T, (Type? CaseType, object? CaseValue)>? UnionDeconstructor { get; init; }
}

[EditorBrowsable(EditorBrowsableState.Never)]
public static partial class JsonMetadataServices
{
    public static JsonTypeInfo<T> CreateUnionInfo<T>(JsonSerializerOptions options, JsonUnionInfoValues<T> unionInfo) where T : notnull;
}

Alternatives considered

  • $type on union serialization — unions lack a natural discriminator, particularly when union cases are not objects. Discussed under Serialization: no discriminator.
  • Structural matching / content sniffing as defaults — discussed under Why not structural matching or content sniffing?.
  • Built-in classifier factories — deferred. The current design exposes only the abstraction; common policies can be added later as concrete factory subclasses without breaking existing code.

Risks

  • Breaking changes: none — all new surface.
  • Performance: default deserialization is O(1) and zero-buffering. Custom classifiers may opt into read-ahead, with the cost paid only when configured.

Prototype

Branch: json-unions — commit b11e3d00c23.

The prototype additionally implements closed-hierarchy/closed-enum support and the InferDerivedTypes API surface, which are deliberately out of scope for this issue and will be proposed separately once the corresponding compiler features ship.

Activity

  1. added
    api-suggestion
    on Apr 22, 2026
  2. added
    untriaged
    on Apr 22, 2026
  3. dotnet-policy-service commented on Apr 22, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-text-json
    See info in area-owners.md if you want to be subscribed.

  4. added
    api-ready-for-review
    and removed
    untriaged
    api-suggestion
    on Apr 22, 2026
  5. added this to the 11.0.0 milestone on Apr 22, 2026
  6. aromaa commented on Apr 22, 2026

    @aromaa
    Contributor

    While I agree on the decision to not include $type on unions, would it still make sense to allow the developer to opt in to it by explicitly specifying the indies by themselves by either providing them in the contract model or as an attribute? Or perhaps extend the JsonTypeClassifierFactory to allow providing reader and writer so the developer can do it by themselves?

    Currently the polymorphic serialization has some pain points around generics and unions could come in handy to solve this. For example, say you have abstract class Foo<T> and class Bar<T> : Foo<T> and on your JSON class you would like to define a Foo<int>. This does not work because there is no natural way to define this without it being ambiguous. You could also not have the T in the base class to begin with. The motivation here is that you can have several different T's in that same JSON but share code.

    Currently this requires either code duplication or custom serializer. There is also no way to define different types for the same Type across different properties. One other way to hack around it is define a custom serializer that takes different JsonSerializerOptions that has been customized per property using contracts.

    Now, this could be solved with unions by defining a union like Value<T>(Foo<T>) and then you can define a Value<int> in the JSON class instead, solving this particular problem.

  7. added
    blocking
    on Apr 23, 2026
  8. eiriktsarpalis commented on Apr 23, 2026

    @eiriktsarpalis
    MemberAuthor

    While I agree on the decision to not include $type on unions, would it still make sense to allow the developer to opt in to it by explicitly specifying the indies by themselves by either providing them in the contract model or as an attribute?

    It's something I looked into, at the end of the day from an API complexity perspective it made more sense to segregate the serialization semantics of the two kinds. We're also planning on releasing closed hierarchies so you will be getting the same exhaustiveness analysis goodness in the polymorphism world if you need it.

    Currently the polymorphic serialization has some pain points around generics and unions could come in handy to solve this. For example, say you have abstract class Foo and class Bar : Foo and on your JSON class you would like to define a Foo. This does not work because there is no natural way to define this without it being ambiguous. You could also not have the T in the base class to begin with. The motivation here is that you can have several different T's in that same JSON but share code.

    So effectively you'd want this to work?

    using System.Text.Json;
    using System.Text.Json.Serialization;
    
    JsonSerializer.Serialize<Foo<int>>(new Bar<int>());
    
    [JsonDerivedType(typeof(Bar<>), "bar")]
    public class Foo<T>;
    
    public class Bar<T> : Foo<T>;

    I think we could just try to support that without it impacting our unions discussions. Do you want to file an issue?

  9. aromaa commented on Apr 23, 2026

    @aromaa
    Contributor

    Do you want to file an issue?

    I have filed #127317.

  10. mikekistler commented on Apr 26, 2026

    @mikekistler

    Re:

    For example, union(string, int) produces:

    {
      "anyOf": [
        { "type": "string" },
        { "type": "integer" }
      ]
    }
    

    In general this looks right but this particular case could be simpler, producing just:

    {
      "type": ["string", "integer"]
    }
    

    Will there be any attempt to produce these simpler forms when possible, or an extension point so that a user could do so if they wanted to?

  11. eiriktsarpalis commented on Apr 27, 2026

    @eiriktsarpalis
    MemberAuthor

    Will there be any attempt to produce these simpler forms when possible, or an extension point so that a user could do so if they wanted to?

    It's possible to allow simplifications of the schema when possible, the downside being that the resultant schema might be more difficult to anticipate as configuration changes. For example, customizing the JsonNumberHandling for a given integer type may introduce additional keywords (e.g. "pattern") that render the same simplification impossible so the schema reverts back to using anyOf.

  12. KevinCathcart commented on Apr 27, 2026

    @KevinCathcart
    Contributor

    So with this proposal if I have an ambiguous union as a property in my type, but am happy with discriminator style resolution, would just applying [JsonPolymorphic] simply work (possibly requiring explicitly listing the cases with [JsonDerivedType(...)] to specify the descrinator values)? Or am I forced to set up a classifier?

    I would hope that the the former could be made to work, such that users with a an ambiguous union can simply choose if they want a tagged representation by opting in with attributes, or they can choose a direct representation, in which case they must implement a classifier to support deserialization.

    The main issue is can see is that a descrinunator field can only be added to object types, so the other types would need a wrapper object with the desriminator and a value property, where the latter holds the actual value. Which is fine, but it would be weird to skip the same structure for object types, however for a union with only object types, I could easilly see somebody wanting to skip the wrapper, especially if it lets them switch from an artificial empty base class to a union type.

  13. eiriktsarpalis commented on Apr 27, 2026

    @eiriktsarpalis
    MemberAuthor

    So with this proposal if I have an ambiguous union as a property in my type, but am happy with discriminator style resolution, would just applying [JsonPolymorphic] simply work (possibly requiring explicitly listing the cases with [JsonDerivedType(...)] to specify the descrinator values)? Or am I forced to set up a classifier?

    You would need to model your type as a type hierarchy, unions do not support emitting discriminators at all under this proposal. As you point out, discriminators only really work well if all the union cases serialize as objects which is not always the case in union types.

  14. bartonjs commented on Apr 28, 2026

    @bartonjs
    Member

    Video

    • JsonSerializerOptions.UnionClassifiers => JsonSerializerOptions.TypeClassifiers
    • JsonSourceGenerationOptionsAttribute.UnionClassifiers => JsonSourceGenerationOptionsAttribute.TypeClassifiers
    • There was a lot of discussion around trying to make union Pet(Cat, Dog) work out of the box, but no good conclusions were arrived at.
    namespace System.Text.Json.Serialization
    {
        // Classifier abstraction
    
        public delegate Type? JsonTypeClassifier(ref Utf8JsonReader reader);
    
        public sealed class JsonTypeClassifierContext
        {
            public Type DeclaringType { get; }
            public IReadOnlyList<JsonUnionCaseInfo> UnionCases { get; }
            public IReadOnlyList<JsonDerivedType> DerivedTypes { get; }
            public string? TypeDiscriminatorPropertyName { get; }
        }
    
        public abstract class JsonTypeClassifierFactory
        {
            public abstract bool CanClassify(Type declaringType);
            public abstract JsonTypeClassifier CreateJsonClassifier(
                JsonTypeClassifierContext context, JsonSerializerOptions options);
        }
    
        public abstract class JsonTypeClassifierFactory<T> : JsonTypeClassifierFactory
        {
            public sealed override bool CanClassify(Type declaringType) => declaringType == typeof(T);
        }
    
        // New options-level surface
    
        public sealed partial class JsonSerializerOptions
        {
            public IList<JsonTypeClassifierFactory> Classifiers { get; }
        }
    
        public sealed partial class JsonSourceGenerationOptionsAttribute
        {
            public Type[]? Classifiers { get; set; }
        }
    
        // New attribute APIs
    
        [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)]
        public sealed class JsonUnionAttribute : JsonAttribute
        {
            [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]
            public Type? TypeClassifier { get; set; }
        }
    
        public sealed partial class JsonPolymorphicAttribute
        {
            [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]
            public Type? TypeClassifier { get; set; }
        }
    }
    
    namespace System.Text.Json.Serialization.Metadata
    {
        // Contract customization surface for union types
    
        public sealed class JsonUnionCaseInfo
        {
            public JsonUnionCaseInfo(Type caseType);
            public Type CaseType { get; }
            public bool IsNullable { get; init; }
        }
    
        public enum JsonTypeInfoKind
        {
            Union = 4,
        }
    
        public abstract partial class JsonTypeInfo
        {
            public JsonTypeClassifier? TypeClassifier { get; set; }
            public IList<JsonUnionCaseInfo>? UnionCases { get; set; }
            public Func<Type, object?, object>? UnionConstructor { get; set; }
            public Func<object, (Type? CaseType, object? CaseValue)>? UnionDeconstructor { get; set; }
        }
    
        public sealed partial class JsonTypeInfo<T>
        {
            public new Func<Type, object?, T>? UnionConstructor { get; set; }
            public new Func<T, (Type? CaseType, object? CaseValue)>? UnionDeconstructor { get; set; }
        }
    
        [EditorBrowsable(EditorBrowsableState.Never)]
        public sealed class JsonUnionInfoValues<T>
        {
            public IList<JsonUnionCaseInfo>? UnionCases { get; init; }
            public Func<Type, object?, T>? UnionConstructor { get; init; }
            public JsonTypeClassifier? TypeClassifier { get; init; }
            public Func<T, (Type? CaseType, object? CaseValue)>? UnionDeconstructor { get; init; }
        }
    
        [EditorBrowsable(EditorBrowsableState.Never)]
        public static partial class JsonMetadataServices
        {
            public static JsonTypeInfo<T> CreateUnionInfo<T>(JsonSerializerOptions options, JsonUnionInfoValues<T> unionInfo) where T : notnull;
        }
    }
  15. added
    api-approved
    and removed
    blocking
    api-ready-for-review
    on Apr 28, 2026
  16. eiriktsarpalis commented on May 13, 2026

    @eiriktsarpalis
    MemberAuthor

    The implementation has made a few amendments to the approved surface. The updated shape has been submitted for approval to FXDC.

    • JsonSerializerOptions.Classifiers and JsonSourceGenerationOptionsAttribute.Classifiers were renamed to TypeClassifiers to match JsonTypeClassifier / JsonTypeClassifierFactory and avoid an unqualified Classifiers property on options bags.
    • JsonTypeClassifierFactory.CanClassify(Type) was changed to CanClassify(JsonTypeClassifierContext) so factories can distinguish union and polymorphic-type contexts and inspect the available cases / derived types without accessing serializer options.
    • JsonTypeClassifierKind and JsonTypeClassifierContext.Kind were added; the enum values are None = 0, Union = 1, and PolymorphicType = 2.
    • JsonTypeClassifierContext remains runtime-created; it has no public constructor.
    • Source-generation metadata bags now carry polymorphism/classifier metadata: JsonObjectInfoValues<T> and JsonCollectionInfoValues<TCollection> include PolymorphismOptions and TypeClassifierFactory, and JsonUnionInfoValues<T> includes TypeClassifierFactory.
    namespace System.Text.Json
    {
        public sealed partial class JsonSerializerOptions
        {
            // As approved
            // public IList<JsonTypeClassifierFactory> Classifiers { get; }
    
            public IList<JsonTypeClassifierFactory> TypeClassifiers { get; }
        }
    }
    
    namespace System.Text.Json.Serialization
    {
        // Classifier abstraction
    
        public delegate Type? JsonTypeClassifier(ref Utf8JsonReader reader);
    
        public sealed class JsonTypeClassifierContext
        {
            public JsonTypeClassifierKind Kind { get; }
            public Type DeclaringType { get; }
            public IReadOnlyList<JsonUnionCaseInfo> UnionCases { get; }
            public IReadOnlyList<JsonDerivedType> DerivedTypes { get; }
            public string? TypeDiscriminatorPropertyName { get; }
        }
    
        public abstract class JsonTypeClassifierFactory
        {
            // As approved
            // public abstract bool CanClassify(Type declaringType);
    
            public abstract bool CanClassify(JsonTypeClassifierContext context);
            public abstract JsonTypeClassifier CreateJsonClassifier(
                JsonTypeClassifierContext context, JsonSerializerOptions options);
        }
    
        public abstract class JsonTypeClassifierFactory<T> : JsonTypeClassifierFactory
        {
            // As approved
            // public sealed override bool CanClassify(Type declaringType);
    
            public sealed override bool CanClassify(JsonTypeClassifierContext context);
        }
    
        public enum JsonTypeClassifierKind
        {
            None = 0,
            Union = 1,
            PolymorphicType = 2,
        }
    
        // Options-level source generation surface
    
        public sealed partial class JsonSourceGenerationOptionsAttribute
        {
            // As approved
            // public Type[]? Classifiers { get; set; }
    
            public Type[]? TypeClassifiers { get; set; }
        }
    
        // Attribute APIs
    
        [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)]
        public sealed class JsonUnionAttribute : JsonAttribute
        {
            [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]
            public Type? TypeClassifier { get; set; }
        }
    
        public sealed partial class JsonPolymorphicAttribute
        {
            [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]
            public Type? TypeClassifier { get; set; }
        }
    }
    
    namespace System.Text.Json.Serialization.Metadata
    {
        // Contract customization surface for union types
    
        public sealed class JsonUnionCaseInfo
        {
            public JsonUnionCaseInfo(Type caseType);
            public Type CaseType { get; }
            public bool IsNullable { get; init; }
        }
    
        public enum JsonTypeInfoKind
        {
            Union = 4,
        }
    
        public abstract partial class JsonTypeInfo
        {
            public JsonTypeClassifier? TypeClassifier { get; set; }
            public IList<JsonUnionCaseInfo> UnionCases { get; }
            public Func<Type, object?, object>? UnionConstructor { get; set; }
            public Func<object, (Type? CaseType, object? CaseValue)>? UnionDeconstructor { get; set; }
        }
    
        public sealed partial class JsonTypeInfo<T>
        {
            public new Func<Type, object?, T>? UnionConstructor { get; set; }
            public new Func<T, (Type? CaseType, object? CaseValue)>? UnionDeconstructor { get; set; }
        }
    
        [EditorBrowsable(EditorBrowsableState.Never)]
        public sealed class JsonUnionInfoValues<T>
        {
            public JsonTypeClassifier? TypeClassifier { get; init; }
            public JsonTypeClassifierFactory? TypeClassifierFactory { get; init; }
            public IList<JsonUnionCaseInfo>? UnionCases { get; init; }
            public Func<Type, object?, T>? UnionConstructor { get; init; }
            public Func<T, (Type? CaseType, object? CaseValue)>? UnionDeconstructor { get; init; }
        }
    
        [EditorBrowsable(EditorBrowsableState.Never)]
        public static partial class JsonMetadataServices
        {
            public static JsonTypeInfo<T> CreateUnionInfo<T>(JsonSerializerOptions options, JsonUnionInfoValues<T> unionInfo)
                where T : notnull;
        }
    
        [EditorBrowsable(EditorBrowsableState.Never)]
        public sealed class JsonObjectInfoValues<T>
        {
            public JsonPolymorphismOptions? PolymorphismOptions { get; init; }
            public JsonTypeClassifierFactory? TypeClassifierFactory { get; init; }
        }
    
        [EditorBrowsable(EditorBrowsableState.Never)]
        public sealed class JsonCollectionInfoValues<TCollection>
        {
            public JsonPolymorphismOptions? PolymorphismOptions { get; init; }
            public JsonTypeClassifierFactory? TypeClassifierFactory { get; init; }
        }
    }
  17. added a commit that references this issue on May 21, 2026
    b521e15
  18. locked and limited conversation to collaborators on Jun 20, 2026
  19. added a commit that references this issue on Jul 15, 2026
    64be7c9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

api-approvedarea-System.Text.Json

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions