Serialize and deserialize enum as string with System.Text.Json
A few different wasy to achive the same goal. For more comprehensive documentation, refer to JSON in .NET.
Deserialize string value into enum
Attribute
use JsonConverter and JsonStringEnumConverter.
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum AccountIdKind
{
Iban = 1,
Bban = 2
}
Configure in Startup
public void ConfigureServices(IServiceCollection services)
{
...
services.AddControllers()
.AddJsonOptions(x =>
{
x.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
Serialize enum as string in Refit
services.AddSingleton(x =>
{
var hostUrl = new Uri(configuration["Api:BaseUrl"]);
var subscriptionKey = configuration["Api:SubscriptionKey"];
var headerClientHandler = new HeaderClientHandler(subscriptionKey);
var jsonSerializerOptions = new JsonSerializerOptions();
jsonSerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));
return RestService.For<ILedgerApi>(
new HttpClient(headerClientHandler) { BaseAddress = hostUrl },
new RefitSettings(new SystemTextJsonContentSerializer(jsonSerializerOptions))
);
});
Comments