In asp.net core 3.1, using the new System.Text.Json, I am trying to use a custom JsonConverter on an appsettings section. Manually serializing/deserializing respects the converter just fine, but reading from appSettings via Options pattern does not. Here's what I have:
The JsonConverter. For simplicity, this one just converts a string value to uppercase:
public class UpperConverter : JsonConverter<string>
{
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
reader.GetString().ToUpper();
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) =>
writer.WriteStringValue(value == null ? "" : value.ToUpper());
}
The appsettings class, declaring the converter on a string property:
public class MyOptions
{
public const string Name = "MyOptions";
[JsonConverter(typeof(UpperConverter))]
public string MyString { get; set; }
}
The Startup.cs changes to prepare everything:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new UpperConverter());
});
services.Configure<MyOptions>(Configuration.GetSection(MyOptions.Name));
}
When I inject an IOptions<MyOptions>
into the HomeController, it reads a lowercase value. If I manually do JsonSerializer.Deserialize<MyOptions>("{\"MyString\":\"lowercase_manual\"}")
, I get an uppercase string. Even when I remove Startup declarations of JsonSerializerOptions.
Does anyone know how to get the appsettings / options pattern to respect the JsonConverter? Do I have to declare the JsonSerializerOptions somewhere else? Thanks.