ardalis / ardalis/SmartEnum

Deserialization of appsettings.json via ConfigurationBuilder doesn't work

Open
#399 1 comment 5 reactions 0 assignees View on GitHub
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

Open the contributing 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.