【问题标题】:Read JSON as string from Microsoft.Extensions.Configuration从 Microsoft.Extensions.Configuration 将 JSON 作为字符串读取
【发布时间】:2020-07-13 15:30:01
【问题描述】:

Microsoft.Extensions.Configuration 有自己的 API,用于浏览它读取的配置文件中包含的 JSON。(这是 ASP.NET 用于配置的内容)

对于给定的 JSON 节点,有没有办法以字符串而不是更多配置对象的形式访问其内容?我的配置文件中有 JSON 对象,我需要通过 JSON 反序列化程序运行(所以我只想从文件中读取这个节点作为字符串)。

类似于以下内容:

var myObjectsSection = configuration.GetSection("MyObjects");
var innerText = myObjectsSection.InnerText; //Is there any way to do this???
var myObjs = JsonConvert.DeserializeObject<MyObject[]>(innerText);

配置文件:

{
   "SomeSetting": "mySetting",
   "MyObjects": [
        {
            ...
        },
        {
            ...
        }
   ]
}

【问题讨论】:

    标签: c# .net json asp.net-core microsoft.extensions.configuration


    【解决方案1】:

    Asp.net core 3 有获取类型相关配置值的方法:T IConfigurationSection.Get&lt;T&gt;()

    我已尝试解析您描述的自定义配置并且它正在工作。

    appsetting.json:

    {
      "CustomSection": [
        {
          "SomeProperty": 1,
          "SomeOtherProperty": "value1"
        }
      ]
    }
    
    

    启动类:

    public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                this.Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            public void ConfigureServices(IServiceCollection services)
            {
                IConfigurationSection section = this.Configuration.GetSection("CustomSection");
                var configs = section.Get<List<CustomSectionClass>>();
            }
    
            public class CustomSectionClass
            {
                public int SomeProperty { get; set; }
                
                public string SomeOtherProperty { get; set; }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-14
      • 1970-01-01
      相关资源
      最近更新 更多