Home > database >  StringEnumConverter with Swagger
StringEnumConverter with Swagger

Time:07-27

I'm using .Net Core 3.1 and some class have enums, and I'd like tha swagger API return enum as string.

Fox example:

namespace Model.Settings
{
    public enum SensorType
    {
        NONE = 0,
        IN = 1,
        OUT = 2
    }
}

......

namespace Model.Settings
{
    [JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
    public class SensorsSettings
    {
        [BsonElement("inOutDistance")]
        [Required]
        public int InOutDistance { get; set; }

        [BsonElement("type")]
        [BsonRepresentation(BsonType.String)]
        [JsonConverter(typeof(StringEnumConverter))]
        [Required]
        public SensorType[] Type { get; set; }
    }
}

So, when I call Http GET at API, I receive this JSON:

"sensorsSettings": {
      "inOutDistance": 65,
      "type": [
        1,
        2,
        0,
        0
      ]
    },

But I'd like:

"sensorsSettings": {
      "inOutDistance": 65,
      "type": [
        "IN",
        "OUT",
        "NONE",
        "NONE"
      ]
    },

Where I'm wrong?

<PackageReference Include="Swashbuckle.AspNetCore" Version="5.5.1" />
<PackageReference Include="Swashbuckle.AspNetCore.Newtonsoft" Version="5.5.1" />

Could you help me?

CodePudding user response:

So yeah as you mentioned in comments the answer is to change [JsonConverter(typeof(StringEnumConverter))] attribute to [JsonProperty("type", ItemConverterType=typeof(StringEnumConverter))] attribute.


You can also convert enums without these attributes.

Just add this to your services:

services.AddControllers()
    .AddJsonOptions(o => o.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));
  • Related