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

Add support for non-string discriminators using System.Text.Json #1724

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,46 @@ public async Task When_using_native_attributes_in_SystemTextJson_then_schema_is_
""".ReplaceLineEndings(), data);
}

public class Dalmation : Dog
{
public string Foo { get; set; }
}

public class Poodle : Dog
{
public string Bar { get; set; }
}

[JsonDerivedType(typeof(Dalmation), 1)]
[JsonDerivedType(typeof(Poodle), 2)]
[JsonPolymorphic(TypeDiscriminatorPropertyName = "breed")]
public class Dog
{
public string Baz { get; set; }
}

[Fact]
public async Task When_using_native_attributes_and_integer_discriminator_in_SystemTextJson_then_schema_is_correct()
{
//// Act
var schema = JsonSchema.FromType<Dog>();
var data = schema.ToJson().ReplaceLineEndings();

//// Assert
Assert.NotNull(data);
Assert.Contains(@"""1"": """, data);
Assert.Contains(@"""2"": """, data);
Assert.Contains(
"""
"discriminator": {
"propertyName": "breed",
"mapping": {
"1": "#/definitions/Dalmation",
"2": "#/definitions/Poodle"
}
},
""".ReplaceLineEndings(), data);
}
#endif
}
}
4 changes: 2 additions & 2 deletions src/NJsonSchema/Generation/JsonSchemaGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1141,9 +1141,9 @@ public SystemTextJsonInheritanceWrapper(string discriminatorName, dynamic[] json

public string DiscriminatorName { get; }

public string GetDiscriminatorValue(Type type)
public string? GetDiscriminatorValue(Type type)
{
return _jsonDerivedTypeAttributes.FirstOrDefault(a => a.DerivedType == type)?.TypeDiscriminator
return _jsonDerivedTypeAttributes.FirstOrDefault(a => a.DerivedType == type)?.TypeDiscriminator?.ToString()
?? throw new InvalidOperationException($"Discriminator value for {type.FullName} not found.");
}
}
Expand Down
Loading