如何使用值数组读取appsettings.json [英] How to read appsettings.json with array of values

查看:85
本文介绍了如何使用值数组读取appsettings.json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下appSettings.json文件:

I have the following appSettings.json file:

  "SundrySettings": {

    "CookieName": "Cookie",

    "AccessGroup": "Software Development",

    "Terminals" :  {
      "Raucherplatz" : "tablet1.local",
      "Service" :      "tablet2.local",  
      "Technik" :      "tablet3.local",  
      "Technik" :      "tablet4.local",  
      "Container" :    "tablet5.local"
    }
  }
}

我想加载到以下结构中:

That I would like to load into the following structure:


    public class Terminal
    {
        public string Name;
        public string Description;
    }

    public class SundryOptions
    {
        public string CookieName { get; set; } = "dummy";
        public string HRAccessGroup { get; set; } = "dummy";
        public List<Terminal> Terminals;
    }

我将尝试使用以下命令加载:

that I would try to load using the following commands:

ServiceProvider sp = services.BuildServiceProvider();
SundryOptions sundryOptions = sp.GetService<IOptions<SundryOptions>>().Value;

我遇到的问题是,使用属性初始化程序永远不会正确设置终端列表.我确实需要一个列表(而不是字典),因为实体可能是双重的,即在我的示例中为Technik.

The problem I have is that using Property Initialisers never sets the Terminals List correctly. I do need a list (and not a Dictionary) as the enties could be double i.e. Technik in my example.

我假设我在Class中有一些错误->对于任何指针我都会很高兴.

I am assuming that I have some error in the Class -> I would be happy for any pointers.

推荐答案

对配置的实现如下所示:

Implement processing of configuration as following somewhere approporiate like this:

var cookieName = 
Configuration.GetSection("SundrySettings:CookieName").Value;
var accessGroup = Configuration.GetSection("SundrySettings:AccessGroup").Value;

var terminals = new List<Terminal>()

var terminalSections = this.Configuration.GetSection("Terminals").GetChildren();
foreach (var item in terminalSections)
{
    terminals.Add(new Terminal 
    {
           // perform type mapping here 
    });
}

SundryOptions sundryOption = new SundryOptions()
{
        CookieName = cookieName,
        HRAccessGroup = accessGroup,
        Terminals = terminalList
};

当然可以有较短的版本,但是您可以从这里开始.

Of course there could be shorter version, but you can start from here.

这篇关于如何使用值数组读取appsettings.json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆