TL;DR: How do I read a complex JSON object from appsettings.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"
}
}
}
}
}
}
I am able to read the simple config values (key:value pairs) without issue by calling Configuration.GetValue<string>("ElasticSearch:MyIndex:index")
.
Configuration.GetSection
Configuration.GetSection("ElasticSearch:MyIndex:mappings").Value
gives me a null
value for Value
.
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.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.
Dictionary<string,object> settings = Configuration
.GetSection("ElasticSearch")
.Get<Dictionary<string,object>>();
string json = JsonConvert.SerializeObject(settings);
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"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With