Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[API Proposal]: JsonDerivedTypeAttribute<T> for simplified polymorphic JSON configuration #99421

Closed
kzu opened this issue Mar 7, 2024 · 1 comment
Labels
api-suggestion Early API idea and discussion, it is NOT ready for implementation area-System.Text.Json

Comments

@kzu
Copy link
Contributor

kzu commented Mar 7, 2024

Background and motivation

You currently have to decide on a "discriminator name" for derived types, such as:

[JsonDerivedType(typeof(MessageContent), nameof(MessageContent)]
[JsonDerivedType(typeof(FileContent), nameof(FileContent)]
public abstract record Content ...

In many cases, choosing the type name as the discrimantor makes perfect sense.
Since attributes can now be generic, it would make sense to leverage that to simplify the annotation.

API Proposal

public class JsonDerivedTypeAttribute<T> : JsonDerivedTypeAttribute
{
    public JsonDerivedTypeAttribute(string? typeDiscriminator = default) : base(typeof(T), typeDiscriminator ?? typeof(T).Name)
    {
    }
}```


### API Usage

```csharp
[JsonDerivedType<MessageContent>]
[JsonDerivedType<FileContent>("file")]
public abstract record Content ...

Alternative Designs

Perhaps the overload to override the discriminator string is unnecessary?

Risks

No response

@kzu kzu added the api-suggestion Early API idea and discussion, it is NOT ready for implementation label Mar 7, 2024
@dotnet-policy-service dotnet-policy-service bot added the untriaged New issue has not been triaged by the area owner label Mar 7, 2024
@eiriktsarpalis
Copy link
Member

Duplicate of #72936.

@dotnet-policy-service dotnet-policy-service bot removed the untriaged New issue has not been triaged by the area owner label Mar 11, 2024
@github-actions github-actions bot locked and limited conversation to collaborators Apr 12, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
api-suggestion Early API idea and discussion, it is NOT ready for implementation area-System.Text.Json
Projects
None yet
Development

No branches or pull requests

2 participants