Published: February 10 2023

C# + .NET 7.0 - Serialize (Convert) Enum to String in API Response

Built with .NET 7.0

This is a quick post to show how to configure an ASP.NET Core API to serialize all enum properties to strings in HTTP responses.

By default enum properties are returned as a number, for example if you have the following enum for user roles:

public enum Role
{
    Admin,
    User
}

A user with the Role = Role.Admin would be returned from the API as "role": 0, e.g:

{
    "id": 1,
    "title": "Mr",
    "firstName": "George",
    "lastName": "Costanza",
    "email": "[email protected]",
    "role": 0
}


Convert Enums to Strings with JsonStringEnumConverter

To convert enums to strings in API responses so the above role would return the value "role": "Admin", add a call to .AddJsonOptions() after services.AddControllers() in the Program.cs file, and add a new JsonStringEnumConverter() to the JsonSerializerOptions.Converters list like the following.

services.AddControllers().AddJsonOptions(x =>
{
    // serialize enums as strings in api responses (e.g. Role)
    x.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});


Example .NET 7 Program.cs File

Below is a complete .NET 7 Program file that includes the above snippet to convert enums to strings. It's from a CRUD API tutorial I posted recently, the complete project and documentation is available at .NET 7.0 + Dapper + SQLite - CRUD API Tutorial in ASP.NET Core.

The Program file configures dependency injection, initializes a SQLite database, configures the HTTP request pipeline and starts the API.

using System.Text.Json.Serialization;
using WebApi.Helpers;
using WebApi.Repositories;
using WebApi.Services;

var builder = WebApplication.CreateBuilder(args);

// add services to DI container
{
    var services = builder.Services;
    var env = builder.Environment;
 
    services.AddSingleton<DataContext>();
    services.AddCors();
    services.AddControllers().AddJsonOptions(x =>
    {
        // serialize enums as strings in api responses (e.g. Role)
        x.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());

        // ignore omitted parameters on models to enable optional params (e.g. User update)
        x.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
    });
    services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

    // configure DI for application services
    services.AddScoped<IUserRepository, UserRepository>();
    services.AddScoped<IUserService, UserService>();
}

var app = builder.Build();

// ensure database and tables exist
{
    using var scope = app.Services.CreateScope();
    var context = scope.ServiceProvider.GetRequiredService<DataContext>();
    await context.Init();
}

// configure HTTP request pipeline
{
    // global cors policy
    app.UseCors(x => x
        .AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader());

    // global error handler
    app.UseMiddleware<ErrorHandlerMiddleware>();

    app.MapControllers();
}

app.Run("http://localhost:4000");

 


Need Some .NET Help?

Search fiverr for freelance .NET developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by