Skip to content

Commit

Permalink
Add support for non-string discriminators (#1724)
Browse files Browse the repository at this point in the history
  • Loading branch information
david-brink-talogy authored Nov 19, 2024
1 parent e168e77 commit 590632a
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,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

0 comments on commit 590632a

Please sign in to comment.