Skip to content
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
19 changes: 19 additions & 0 deletions src/NJsonSchema.Tests/Generation/AttributeGenerationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -354,5 +354,24 @@ public void When_property_has_required_keyword_then_it_is_required_in_Newtonsoft
Assert.DoesNotContain("Optional", schema.RequiredProperties);
}
#endif

#if NET6_0_OR_GREATER
[Display(Name = "My Title", Description = "My Description")]
public class ClassWithDisplayAttribute
{
public string Foo { get; set; }
}

[Fact]
public void When_class_has_Display_Name_then_schema_title_is_set()
{
// Act
var schema = NewtonsoftJsonSchemaGenerator.FromType<ClassWithDisplayAttribute>();

// Assert
Assert.Equal("My Title", schema.Title);
Assert.Equal("My Description", schema.Description);
}
#endif
}
}
11 changes: 11 additions & 0 deletions src/NJsonSchema/Generation/JsonSchemaGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -545,6 +545,17 @@ protected virtual void GenerateObject(JsonSchema schema, JsonTypeDescription typ
schema.Description = type.ToCachedType().GetDescription(Settings);
schema.Example = GenerateExample(type.ToContextualType());

dynamic? displayAttribute = type.GetCustomAttributes(false)
.FirstAssignableToTypeNameOrDefault("System.ComponentModel.DataAnnotations.DisplayAttribute");
if (displayAttribute != null)
{
string? name = displayAttribute.GetName();
if (name != null)
{
schema.Title = name;
}
}

dynamic? obsoleteAttribute = type.GetCustomAttributes(false).FirstAssignableToTypeNameOrDefault("System.ObsoleteAttribute");
if (obsoleteAttribute != null)
{
Expand Down