从appsettings.json

时间:2018-02-22 17:49:15

标签: json .net-core configuration-files

TL; DR:如何从appsettings.json读取复杂的JSON对象?

我有一个具有多种配置值的.NET Core 2.x应用程序。 appsettings.json看起来像下面的代码段,我试图将ElasticSearch:MyIndex:mappings的值作为单个字符串或JSON对象读取。

{
"ConnectionStrings": {
    "redis": "localhost"
},
"Logging": {
    "IncludeScopes": false,
    "Debug": {
        "LogLevel": {
            "Default": "Warning"
        }
    },
    "Console": {
        "LogLevel": {
            "Default": "Warning"
        }
    }
},
"ElasticSearch": {
    "hosts": [ "http://localhost:9200" ],
    "MyIndex": {
        "index": "index2",
        "type": "mytype",
        "mappings": {
            "properties": {
                "property1": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "location": {
                    "type": "geo_point"
                },
                "code": {
                    "type": "string",
                    "index": "not_analyzed"
                }
            }
        }
    }
}
}

通过调用Configuration.GetValue<string>("ElasticSearch:MyIndex:index"),我可以毫无问题地阅读简单的配置值(键:值对)。

Configuration.GetSection Configuration.GetSection("ElasticSearch:MyIndex:mappings").Valuenull提供Value值。

Configuration.GetValue Configuration.GetValue<string>("ElasticSearch:MyIndex:mappings")也返回空值。这对我来说很有意义,因为该部分基于上述尝试具有空值。

Configuration.GetValue Configuration.GetValue<JToken>("ElasticSearch:MyIndex:mappings")也返回空值。由于与上述相同的原因,这对我也有意义。

5 个答案:

答案 0 :(得分:2)

Dictionary<string,object> settings = Configuration
    .GetSection("ElasticSearch")
    .Get<Dictionary<string,object>();
string json = JsonConvert.SerializeObject(settings);

答案 1 :(得分:1)

解决方案最终比我最初尝试的任何东西都简单得多:将appsettings.json读取为任何其他JSON格式的文件。

<body>
  <div class="sitebg-parent">
    <div class="sitebg"></div>
  </div>
</body>

答案 2 :(得分:0)

将JSON对象转换为转义的字符串。为此,您很可能只需要转义所有双引号并将其放在一行上,这样看起来就像:

"ElasticSearch": "{\"hosts\": [ \"http://localhost:9200\" ],\"MyIndex\": {\"index\"... "

然后您可以将其读取为一个字符串,只需使用以下命令即可对其进行解析:

Configuration["ElasticSearch"]

此解决方案并不适合所有人,因为查看或更新转义的json并不有趣,但是如果您只计划很少对此配置设置进行更改,那么它可能不是最坏的主意。

答案 3 :(得分:0)

@chris313​​89 的解决方案很好,并收到了我的投票。但是,我的情况需要更通用的解决方案。

private static IConfiguration configuration;

public static TConfig ConfigurationJson<TConfig>(this string key)
{
  var keyValue = GetJson();
  return Newtonsoft.Json.JsonConvert.DeserializeObject<TConfig>(keyValue);
  
  string GetJson()
  {
     if (typeof(TConfig).IsArray)
     {
         var dictArray = configuration
             .GetSection(key)
             .Get<Dictionary<string, object>[]>();
                
         return Newtonsoft.Json.JsonConvert.SerializeObject(dictArray);
     }

      var dict = configuration
          .GetSection(key)
          .Get<Dictionary<string, object>[]>();
      return Newtonsoft.Json.JsonConvert.SerializeObject(dict);
   }
}

注意事项:

  • 需要 Nuget `Microsoft.Extensions.Configuration.Binder`
  • 正如上面提到的@chris313​​89,您必须反序列化为字典,然后重新序列化为字符串,否则您会得到空值。这行不通
    configuration
      .GetSection(key)
      .Get<TConfig>()
    
  • 如果您尝试反序列化数组,则需要`Dictionary[]`。这就是为什么其他解决方案有时不起作用的原因。

答案 4 :(得分:0)

我通过将其绑定到一个类来获取配置数据并在任何地方用作服务,在 configureservices 我添加这个类

services.Configure<SiteSettings>(options => Configuration.Bind(options));

然后在控制器中我可以通过依赖注入访问它,如下所示:

private readonly IOptionsSnapshot<SiteSettings> _siteSetting;
public TestController(IOptionsSnapshot<SiteSettings> siteSetting) ......
相关问题