3

Is it possilbe in Swashbuckle.AspNetCore.Swagger (6.1.1) to get such enum with names? I need better names for generate API client for frontend app.

public enum BasketResourceEnum
{
    Stocks = 1,
    Currencies
}

Now I get such representation in json, I need name instead of int values

  "BasketResourceEnum": {
    "enum": [
      1,
      2
    ],
    "type": "integer",
    "format": "int32"
  },
Jacek
  • 11,661
  • 23
  • 69
  • 123
  • Maybe that could help you: https://stackoverflow.com/questions/36452468/swagger-ui-web-api-documentation-present-enums-as-strings – TheTanic Mar 31 '21 at 08:10

3 Answers3

4
services
    .AddControllers()
    .AddJsonOptions(options => 
        options.SerializerSettings.Converters.Add(new StringEnumConverter()));
user3119533
  • 186
  • 1
  • 7
  • How to do that only for specific enums? (I don't want to mess with existing api calls, I only want new enums that are added to the project to be serialized and deserialized as strings) – Thanasis Ioannidis Apr 03 '23 at 11:40
  • @ThanasisIoannidis - You could either opt-in to string conversion by placing a `[JsonConverter(typeof(StringEnumConverter))]` attribute on your new enums or override StringEnumConverter's CanConvert method to specify the types you want to convert as strings. – user3119533 Apr 03 '23 at 21:18
3

If you prefer to use System.Text.Json:

using System.Text.Json.Serialization;
...
var builder = WebApplication.CreateBuilder(args);
builder.Services
    .AddControllers()
    .AddJsonOptions(options => options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));
user1007074
  • 2,093
  • 1
  • 18
  • 22
2

And if you prefer not to choose to serialize enum values as strings but just have the names of their members described in Swagger, you can you the this nuget.

In a minimal API you can:

using Unchase.Swashbuckle.AspNetCore.Extensions.Extensions;
...
builder.Services.ConfigureSwaggerGen(options =>
{
    options.AddEnumsWithValuesFixFilters();
});
Dejan
  • 9,150
  • 8
  • 69
  • 117