从 appsettings.json 读取 JSON 对象 [英] Reading a JSON object from appsettings.json
问题描述
TL;DR:如何从 appsettings.json 读取复杂的 JSON 对象?
TL;DR: How do I read a complex JSON object from appsettings.json?
我有一个具有多种类型配置值的 .NET Core 2.x 应用程序.appsettings.json
看起来像下面的代码片段,我试图将 ElasticSearch:MyIndex:mappings
的值作为单个字符串或 JSON 对象读取.
I have a .NET Core 2.x application with multiple types of configuration values. appsettings.json
looks like the snippet below and I am trying to read the value of ElasticSearch:MyIndex:mappings
as a single string or JSON object.
{
"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
,我可以毫无问题地读取简单的配置值(键:值对).
I am able to read the simple config values (key:value pairs) without issue by calling Configuration.GetValue<string>("ElasticSearch:MyIndex:index")
.
Configuration.GetSectionConfiguration.GetSection("ElasticSearch:MyIndex:mappings").Value
给我一个 null
的 Value
值.
Configuration.GetSection
Configuration.GetSection("ElasticSearch:MyIndex:mappings").Value
gives me a null
value for Value
.
Configuration.GetValueConfiguration.GetValue
也返回空值.这对我来说很有意义,因为基于上述尝试,该部分具有空值.
Configuration.GetValue
Configuration.GetValue<string>("ElasticSearch:MyIndex:mappings")
also returns a null value. This makes sense to me as the section has a null value based on the above attempt.
Configuration.GetValueConfiguration.GetValue
也返回一个空值.出于与上述相同的原因,这对我来说也很有意义.
Configuration.GetValue
Configuration.GetValue<JToken>("ElasticSearch:MyIndex:mappings")
also returns a null value. This makes sense to me as well for the same reason as above.
推荐答案
最终的解决方案比我最初尝试的任何方法都要简单得多:将 appsettings.json 与任何其他 JSON 格式的文件一样读取.
The solution ended up being much simpler than anything I was initially trying: read appsettings.json as any other JSON formatted file.
JToken jAppSettings = JToken.Parse(
File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "appsettings.json"))
);
string mapping = jAppSettings["ElasticSearch"]["MyIndex"]["mappings"];
这篇关于从 appsettings.json 读取 JSON 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!