C#ConfigurationBuilder获取JsonObject

时间:2019-11-19 15:11:48

标签: c# json .net-core-2.2

我在使用配置生成器访问JSON配置文件的值时遇到问题 我的JSON看起来像这样

{
  "item": [
    {
      "valueType": "taktzeit",
      "interval": 3
    },
    {
      "valueType": "werkzeugwechsel",
      "interval": 5
    }
  ]
}

更新 它位于名为Config-> Config / config.json的文件夹中。我设置了属性,所以文件在构建文件夹中

我的代码:

var a = builder.AddJsonFile(Globals.ConfigPath).Build()
                .GetSection("item").GetChildren().ToList().Select(x => x.Value).ToList();

这是我遍历“ a”时得到的结果

enter image description here

看不到我想念的东西。 预先感谢

更新2

我的模特:

public class Config
{
        public List<Item> Item { get; set; }
}

public class Item
{
    public string ValueType { get; set; }
    public int Interval { get; set; }
}

2 个答案:

答案 0 :(得分:2)

更改此

var a = builder.AddJsonFile(Globals.ConfigPath).Build()
            .GetSection("item").GetChildren().ToList().Select(x => x.Value).ToList();

var a = builder.AddJsonFile(Globals.ConfigPath).Build()
            .GetSection("item").Get<List<Item>>();

这将得到Item

的列表

答案 1 :(得分:0)

假设其他所有内容都已配置,只需绑定到所需的对象图即可。

IConfiguration configuration = new ConfigurationBuilder()
                                    .AddJsonFile(Globals.ConfigPath)
                                    .Build();

Config config = configuration.Get<Config>();

参考Configuration in ASP.NET Core