Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deserialization of appsettings.json via ConfigurationBuilder doesn't work #399

Open
gianni-imburse opened this issue May 11, 2023 · 1 comment

Comments

@gianni-imburse
Copy link

gianni-imburse commented May 11, 2023

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<ConfigOptions>()
    ?? throw new ApplicationException("Configuration appsettings files not found");

The property is in a nested object and defined as:

[JsonConverter(typeof(SmartEnumNameConverter<AccountType, int>))]
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<AccountType, int>());
jsonSerializerSettings.Converters.Add(new SmartEnumNameConverter<TenantType, int>());
jsonSerializerSettings.Converters.Add(new SmartEnumNameConverter<UserRoles, int>());
jsonSerializerSettings.Converters.Add(new JsonStringEnumConverter());
var options = JsonSerializer.Deserialize<ConfigOptions>(configFile, jsonSerializerSettings);
@laska-u
Copy link

laska-u commented May 18, 2023

Upvote this one. Currently struggling to bind SmartEnum using IOptions/IOptionsMonitor

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants