Skip to content

Support open generics in polymorphic serialization in System.Text.Json #127317

Closed

Description

@aromaa

Polymorphic serialization currently has no mechanism to have open generics in their derived type declarations. This is particularly useful when you have the same general shape across multiple different fields but define different T's.

It would be useful if something similar to the below would 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>;

To work around this today you either have to duplicate code or create a 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 to define a custom serializer that takes different JsonSerializerOptions that has been customized per property using contracts.

Activity

  1. dotnet-policy-service commented on Apr 23, 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.

  2. MihuBot commented on Apr 23, 2026

    @MihuBot

    I'm a bot. Here is a possible related and/or duplicate issue (I may be wrong):

  3. added
    enhancementProduct code improvement that does NOT require public API changes/additions
    and removed
    untriagedNew issue has not been triaged by the area owner
    on Apr 23, 2026
  4. eiriktsarpalis commented on Apr 23, 2026

    @eiriktsarpalis
    Member

    Note this would only work if the generic of the derived type exactly matches that of the base type. In other words forms such as

    [JsonDerivedType(typeof(Derived<>))]
    class Base;
    
    class Derived<T> : Base;

    or

    [JsonDerivedType(typeof(Derived<>))]
    class Base<T>;
    
    class Derived<T> : Base<int>;

    would get rejected. We might also support more complex forms where similarly the open generic unambiguously points to a specific monomorphization lie this one:

    [JsonDerivedType(typeof(Derived<>))]
    class Base<T>;
    
    class Derived<T> : Base<List<T>>;

    We should add a source generator diagnostic specifically providing this feedback for invalid open generics.

  5. locked and limited conversation to collaborators on Jul 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

area-System.Text.JsonenhancementProduct code improvement that does NOT require public API changes/additions

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions