Reputation: 548
I use, among others, Json.NET and NSwag and generate a swagger document. I have classes, Animal
and Dog : Animal
(inherits from Animal
).
public class Animal
{
//properties
}
public class Dog : Animal
{
[JsonProperty(Order = -2)]
public string Name { get; set; }
}
I have property in Dog
, which is Name
. I want to sort Name
before all of Dog
's properties in the generated Swagger request schema.
Current result:
{
propertyOne: value1, //property of Animal
propertyTwo: value2, //property of Animal
Name: value3 //property of Dog
}
Desired result:
{
Name: value3, //property of Dog is sorted before everything else
propertyOne: value1,
propertyTwo: value2
}
Upvotes: 2
Views: 2037
Reputation: 158
I have done similar sorting but in Swashbuckle, might be similar functionality available in Nswag
Used SchemaFilter to sort properties.
services.AddSwaggerGen(swaggerGenOptions =>
{
.....
swaggerGenOptions.SchemaFilter<SwaggerSchemaFilter>();
}
In schemaFilter, I have used order logic to show all the basic datatype properties in their current oreder and properties which are custom classes in the end. But you can order by name or any other logic.
internal class SwaggerSchemaFilter : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
schema.Properties = schema.Properties
.OrderBy(x => string.IsNullOrWhiteSpace(x.Value.Type) ? "z" : "a")
.ToDictionary(p2 => p2.Key, p2 => p2.Value);
}
}
For custom classes the type was null,
Also, you can get type from (SchemaFilterContext) context and use reflection to get more details.
Upvotes: 3