I'm trying to convert appsettings.json to C# class
I use Microsoft.Extensions.Configuration
to read the configuration from appsettings.json
I write the following code using reflection but I'm looking for a better solution
foreach (var (key, value) in configuration.AsEnumerable())
{
var property = Settings.GetType().GetProperty(key);
if (property == null) continue;
object obj = value;
if (property.PropertyType.FullName == typeof(int).FullName)
obj = int.Parse(value);
if (property.PropertyType.FullName == typeof(long).FullName)
obj = long.Parse(value);
property.SetValue(Settings, obj);
}
Build configuration from appsettings.json file:
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional = false)
.Build()
Then add Microsoft.Extensions.Configuration.Binder nuget package. And you will have extensions to bind configuration (or configuration section) to the existing or new object.
E.g. you have a settings class (btw by convention it's called options)
public class Settings
{
public string Foo { get; set; }
public int Bar { get; set; }
}
And appsettings.json
{
"Foo": "Bob",
"Bar": 42
}
To bind configuration to new object you can use Get<T>()
extension method:
var settings = config.Get<Settings>();
To bind to existing object you can use Bind(obj)
:
var settings = new Settings();
config.Bind(settings);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With