Map appsettings.json to class

Viewed 5290

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);
}
2 Answers

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);

You can use Dictionary to get the json, and then use JsonSerializer to convert the json.

public IActionResult get()
    {
        Dictionary<string, object> settings = configuration
        .GetSection("Settings")
        .Get<Dictionary<string, object>>();
        string json = System.Text.Json.JsonSerializer.Serialize(settings);

        var setting = System.Text.Json.JsonSerializer.Deserialize<Settings>(json);

        return Ok();
    }

Here is the model

public class Settings
{
    public string property1 { get; set; }
    public string property2 { get; set; }
}

In appsettings.json

 "Settings": {
  "property1": "ap1",
  "property2": "ap2"
 },

enter image description here

Related