【问题标题】:C# ConfigurationBuilder Get JsonObjectC# ConfigurationBuilder 获取 JsonObject
【发布时间】:2019-11-19 23:50:52
【问题描述】:

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

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

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

我的代码:

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

这是我循环“a”时得到的结果

看不到我错过了什么。 提前致谢

更新 2

我的模特:

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

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

【问题讨论】:

  • 项目中 Jason 文件的名称是什么?是 appsettings.json 文件吗?
  • 不,它是文件夹中的一个文件:Config/config.json。我已经将文件设置在构建中。如果我使用....GetSection("item:0:valuteTyp").. 我得到文件里面的内容。但我需要更通用的方式
  • 我们能看到这个反序列化到的类吗?您的 LINQ 中似乎有“x.Value”,但 JSON 中有“valueType”。
  • 我更新了我的帖子
  • 试试这个var a = builder.AddJsonFile(Globals.ConfigPath).Build() .GetSection("item").Get&lt;List&lt;Item&gt;&gt;();看看它是否返回列表f Item

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


【解决方案1】:

改变这个

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的列表

【讨论】:

    【解决方案2】:

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

    IConfiguration configuration = new ConfigurationBuilder()
                                        .AddJsonFile(Globals.ConfigPath)
                                        .Build();
    
    Config config = configuration.Get<Config>();
    

    参考Configuration in ASP.NET Core

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-29
      相关资源
      最近更新 更多