Deserialization of appsettings.json via ConfigurationBuilder doesn't work
- Dominant language
- C#
- Stars
- 2.4k
- Forks
- 184
- PR merge metrics
- No merged PRs in 30d
Description
I have an `appsettings.json` file where a property is defined as `"AccountType": "Default"`.
There's a related SmartEnum defined as `public static readonly AccountType Default = new(nameof(Default), 1);`.
Deserialization is done via the `ConfigurationBuilder`:
```
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{environmentName}.json", optional: true, reloadOnChange: true)
.Build();
var options = config.Get()
?? throw new ApplicationException("Configuration appsettings files not found");
```
The property is in a nested object and defined as:
```
[JsonConverter(typeof(SmartEnumNameConverter))]
public AccountType AccountType { get; set; }
```
I have tried deserializing with both name and value, but the property is always `null`.
I confirm that it works if it's manually deserialized
```
var configFile = File.ReadAllText(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "/appsettings.qa.json");
var jsonSerializerSettings = new JsonSerializerOptions()
{
PropertyNameCaseInsensitive = true
};
jsonSerializerSettings.Converters.Add(new SmartEnumNameConverter());
jsonSerializerSettings.Converters.Add(new SmartEnumNameConverter());
jsonSerializerSettings.Converters.Add(new SmartEnumNameConverter());
jsonSerializerSettings.Converters.Add(new JsonStringEnumConverter());
var options = JsonSerializer.Deserialize(configFile, jsonSerializerSettings);
```
Contributor guide
Research direction
Reproduce the nested AccountType binding through ConfigurationBuilder and Get, then compare it with the manually configured JsonSerializer path shown in the report. Done means AccountType is populated from appsettings.json through the configuration path, with a regression test covering the reported input.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- csharp
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 35/100