C
C#2y ago
Hugh

✅ How do I add a JsonConverter subclass to a .NET 7 WebApplication?

I've written a couple of custom JsonConverter classes, and I've been able to get them in place for manual Json serialization/deserialization. However, I haven't managed to get them to be applied when using a Web Application and a class with the [ApiController] attribute. I'm currently setting it up like this:
WebApplicationBuilder builder = WebApplication.CreateBuilder();

builder.Services.Configure<JsonOptions>(options =>
{
RegisterCustomConverters(options.SerializerOptions);
options.SerializerOptions.PropertyNameCaseInsensitive = true;
});
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Logging.ClearProviders();
builder.Logging.AddConsole();

WebApplication app = builder.Build();
WebApplicationBuilder builder = WebApplication.CreateBuilder();

builder.Services.Configure<JsonOptions>(options =>
{
RegisterCustomConverters(options.SerializerOptions);
options.SerializerOptions.PropertyNameCaseInsensitive = true;
});
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Logging.ClearProviders();
builder.Logging.AddConsole();

WebApplication app = builder.Build();
where RegisterCustomConverters() is:
public static void RegisterConverters(JsonSerializerOptions serializerOptions)
{
serializerOptions.Converters.Add(new CustomConverter1());
serializerOptions.Converters.Add(new CustomConverter2());
}
public static void RegisterConverters(JsonSerializerOptions serializerOptions)
{
serializerOptions.Converters.Add(new CustomConverter1());
serializerOptions.Converters.Add(new CustomConverter2());
}
However, RegisterConverters() is never called, and when I sent a post request, it isn't deserialized using the custom converter. Any idea what I'm doing wrong here? Thanks
1 Reply
Hugh
HughOP2y ago
Ah, I appear to have fixed it by changing it to:
builder.Services.AddControllers()
.AddJsonOptions(options =>
{
SWJsonConverters.RegisterConverters(options.JsonSerializerOptions);
options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
});
builder.Services.AddControllers()
.AddJsonOptions(options =>
{
SWJsonConverters.RegisterConverters(options.JsonSerializerOptions);
options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
});
Want results from more Discord servers?
Add your server