mnc
mnc

Reputation: 548

Order property of derived class first in Swagger schema

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

Answers (1)

Haseeb Mukhtar
Haseeb Mukhtar

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

Related Questions