Skip to content

Inheritance bug: wrong use of JsonDerivedTypeAttribute is required #1783

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

Open
PeterDraex opened this issue Mar 13, 2025 · 1 comment
Open

Comments

@PeterDraex
Copy link

PeterDraex commented Mar 13, 2025

Microsoft docs expects the JsonDerivedType attribute to be applied to the base type:

[JsonDerivedType(typeof(WeatherForecastWithCity))]
public class WeatherForecastBase
{
    public DateTimeOffset Date { get; set; }
    public int TemperatureCelsius { get; set; }
    public string? Summary { get; set; }
}
public class WeatherForecastWithCity : WeatherForecastBase
{
    public string? City { get; set; }
}

But to generate a usable TypeScript code with NSwag, you must put the annotation on both the base and derived types:

[JsonDerivedType(typeof(WeatherForecastWithCity), typeDiscriminator: "this-must-be-specified-but-is-ignored")]
[JsonDerivedType(typeof(WeatherForecastWithVillage), typeDiscriminator: "this-must-be-specified-but-is-ignored2")]
public abstract class WeatherForecastBase
{
    public DateTimeOffset Date { get; set; }
    public int TemperatureCelsius { get; set; }
    public string? Summary { get; set; }
}

[JsonDerivedType(typeof(WeatherForecastWithCity), typeDiscriminator: "this-must-be-specified-but-is-ignored")]
public class WeatherForecastWithCity : WeatherForecastBase
{
    public string? City { get; set; }
}

[JsonDerivedType(typeof(WeatherForecastWithVillage), typeDiscriminator: "this-must-be-specified-but-is-ignored2")]
public class WeatherForecastWithVillage : WeatherForecastBase
{
    public string? Village { get; set; }
}

Only then you get the correct TypeScript:

export interface WeatherForecastBase {
    Date: string;
    TemperatureCelsius: number;
    Summary: string | null;
    $type: string;
}

export interface WeatherForecastWithCity extends WeatherForecastBase {
    City: string | null;
    $type: 'WeatherForecastWithCity';
}

export interface WeatherForecastWithVillage extends WeatherForecastBase {
    Village: string | null;
    $type: 'WeatherForecastWithVillage';
}
@david-brink-talogy
Copy link
Contributor

Aren't you missing [JsonPolymorphic]?

Perhaps these tests are insufficient, but they don't have the extra [JsonDerivedType].

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants