【问题标题】:Get collection from settings.json从 settings.json 获取集合
【发布时间】:2019-02-01 10:37:40
【问题描述】:

我创建了一些 json 格式的配置文件:

{
    "SomeCollection" : [
        {
            "Val1" : "Some string",
            "Val2" : "Some string2"
        }
    ] 
}

我用这个配置创建对象:

IConfiguration config = new ConfigurationBuilder()
      .AddJsonFile("appsettings.json", true, true)
      .Build();

但是我怎样才能得到 Val1 和 Val2 对的列表呢?

【问题讨论】:

  • var section = config.GetSection("SomeCollection"); var val1 = section.GetValue<typeval1>("Val1");
  • 好的,但是文件中可能有n次Val1,Val2对象。你懂我吗?
  • @Igabryel 使用 GetSection 作为字符串并使用 json 进行反序列化
  • 你能给我举个例子吗?
  • 您可以使用以下命令直接将部分转换为类:var section = config.GetSection("SomeCollection") as YourCustomClass; 定义一个包含字典的类,您就可以获得它。或者你可以试试JsonConvert.DeserializeObject<YourClass>(config.GetSection("SomeCollection").ToString());

标签: c# visual-studio-code .net-core


【解决方案1】:

这是我的课:

using System.Collections.Generic;

namespace WebsiteAPI.Models
{
   public class CollectionInAppSettings
   {
        public IDictionary<string,string> SomeCollection { get; set; }
   }
}

这是我的应用设置:

"CollectionInAppSettings": {
    "SomeCollection": {
        "Val1": "Some string",
        "Val2": "Some string2"
    }
}

这是我的 startup.cs 中 ConfigureServices 部分的内容:

services.Configure<CollectionInAppSettings>(Configuration.GetSection("CollectionInAppSettings"));

这是虚拟 HelloController 中的内容:

    private readonly IOptions<CollectionInAppSettings> _options;

    public HelloController(IOptions<CollectionInAppSettings> options)
    {
        _options = options;
    }

    [HttpGet("[action]")]
    public IActionResult IsUp()
    {
        return Ok(_options.Value);
    }

调用端点时: https://localhost:4010/api/hello/isup

这是返回的: "someCollection":{"Val1":"Some string","Val2":"Some string2"}

这里是这个问题的一些其他解决方案的链接:Click here

【讨论】:

    【解决方案2】:

    好的,伙计们。经过几次实验,我得到了解决方案!

    IConfiguration config = new ConfigurationBuilder()
      .AddJsonFile("appsettings.json", true, true)
      .Build();
    foreach( var en in config.GetSection("SomeCollection").GetChildren())
    {
      string Val1= en["Val1"];
      string Val2= en["Val2"];
    }
    

    感谢您的帮助!

    【讨论】:

    • 您应该按照 HenryMigo 的建议使用 IOptions。这绝对是不是推荐的方法(而且您的 JSON 结构不正确)
    猜你喜欢
    • 2011-09-07
    • 1970-01-01
    • 2015-03-05
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多