C# 将appsettings.json映射到类

C# 将appsettings.json映射到类,c#,.net-core,configuration,C#,.net Core,Configuration,我正在尝试将appsettings.json转换为C#class 我使用Microsoft.Extensions.Configuration从appsettings.json读取配置 "Settings": { "property1": "ap1", "property2": "ap2" }, 我使用反射编写以下代码,但我正在寻找更好的解决方案 foreach (var (key,

我正在尝试将appsettings.json转换为C#class

我使用
Microsoft.Extensions.Configuration
从appsettings.json读取配置

 "Settings": {
  "property1": "ap1",
  "property2": "ap2"
 },
我使用反射编写以下代码,但我正在寻找更好的解决方案

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);
}
从appsettings.json文件生成配置:

然后添加Microsoft.Extensions.Configuration.Binder nuget包。您将拥有将配置(或配置节)绑定到现有或新对象的扩展

例如,您有一个设置类(顺便说一句,按照惯例,它被称为选项)

和appsettings.json

 "Settings": {
  "property1": "ap1",
  "property2": "ap2"
 },
要将配置绑定到新对象,可以使用扩展方法:

var settings = config.Get<Settings>();

您可以使用
Dictionary
获取json,然后使用
JsonSerializer
转换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();
    }
在appsettings.json中

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

没有获取和绑定method@AliRezaBeigy然后错过了添加Microsoft.Extensions.Configuration.Binder包的部分
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();
    }
public class Settings
{
    public string property1 { get; set; }
    public string property2 { get; set; }
}
 "Settings": {
  "property1": "ap1",
  "property2": "ap2"
 },