Skip to content

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

@aromaa

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.

Metadata

Metadata

Labels

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

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions