首页 > 解决方案 > 如何为 appsettings.json 复杂数组使用选项模式

问题描述

我在 .NET Core 控制台应用程序中有以下 appsettings.json。此选项模式页面上显示的示例不涵盖复杂类型的应用程序设置。

如何遍历以下应用设置中每种报告类型的列?

{
  "Reports": [
    {
      "name": "Roles",
      "fileName": "roles.csv",
      "columns": [
        {
          "name": "ROLE_ID",
          "default": ""
        },
        {
          "name": "NAME",
          "default": ""
        },
        {
          "name": "AVAILABILITY_IND",
          "default": "YES"
        }
      ]
    },
    {
      "name": "Accounts",
      "fileName": "accounts.csv",
      "columns": [
        {
          "name": "ROLE",
          "default": "NONE"
        },
        {
          "name": "USER_ID",
          "default": ""
        },
        {
          "name": "LASTNAME",
          "default": ""
        },
        {
          "name": "FIRSTNAME",
          "default": ""
        }
      ]
    }
  ]
}

标签: c#asp.net-coreconfigurationsettingsasp.net-core-3.1

解决方案


您可以读取嵌套数组,如下所示:

public class HomeController : Controller
{
    private readonly IConfiguration _configuration;
    public HomeController(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public IActionResult Index()
    {
        //read the first report's columns array's first item's name------"ROLE_ID"
        var data = _configuration.GetSection("Reports:0:columns:0:name");
        return View();
    }

对于如何获取所有键和值

var model = _configuration.GetSection("Reports").AsEnumerable();
foreach (var kv in model)
{
    Console.WriteLine("{0}: {1}", kv.Key, kv.Value);
}

还可以反序列化 json 以建模并从模型中获取项目:

模型:

public class Rootobject
{
    public Report[] Reports { get; set; }
}

public class Report
{
    public string name { get; set; }
    public string fileName { get; set; }
    public Column[] columns { get; set; }
}

public class Column
{
    public string name { get; set; }
    public string _default { get; set; }
}

控制器:

var json = System.IO.File.ReadAllText("yourJsonfile.json");
var DeserializeModel = JsonSerializer.Deserialize<Rootobject>(json);

笔记:

如果你的 json 文件不是默认appsettings.json的,比如:等等。而且test.json你还想从 IConfiguration 中读取它,你需要记住在 Startup.cs 中注册它:

public class Startup
{
    public Startup(IConfiguration configuration, IWebHostEnvironment env)
    {
        configuration = new ConfigurationBuilder().SetBasePath(env.ContentRootPath)
        .AddJsonFile("test.json")
        .Build();

        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
        services.AddSingleton<IConfiguration>(Configuration);
    }
}

推荐阅读