Bab*_*fas 7 json configuration-files .net-core
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"
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我可以通过调用Configuration.GetValue<string>("ElasticSearch:MyIndex:index").
Configuration.GetSection
Configuration.GetSection("ElasticSearch:MyIndex:mappings").Value为我提供了一个null值Value。
Configuration.GetValue
Configuration.GetValue<string>("ElasticSearch:MyIndex:mappings")也返回空值。这对我来说很有意义,因为基于上述尝试,该部分具有空值。
Configuration.GetValue
Configuration.GetValue<JToken>("ElasticSearch:MyIndex:mappings")也返回空值。出于与上述相同的原因,这对我来说也很有意义。
chr*_*389 14
Dictionary<string,object> settings = Configuration
.GetSection("ElasticSearch")
.Get<Dictionary<string,object>>();
string json = JsonConvert.SerializeObject(settings);
Run Code Online (Sandbox Code Playgroud)
该解决方案最终比我最初尝试的任何方法都简单得多:将 appsettings.json 读取为任何其他 JSON 格式的文件。
JToken jAppSettings = JToken.Parse(
File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "appsettings.json"))
);
string mapping = jAppSettings["ElasticSearch"]["MyIndex"]["mappings"];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12214 次 |
| 最近记录: |