TL;博士:如何从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")
来读取简单的配置值(键:值对),而不会出现问题。配置。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")
也返回一个空值。出于与上述相同的原因,这对我也很有意义。
最佳答案
Dictionary<string,object> settings = Configuration
.GetSection("ElasticSearch")
.Get<Dictionary<string,object>>();
string json = JsonConvert.SerializeObject(settings);
关于json - 从appsettings.json读取JSON对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48934081/