Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a JSON object from appsettings.json

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.

like image 842
Babak Naffas Avatar asked Feb 22 '18 17:02

Babak Naffas


2 Answers

Dictionary<string,object> settings = Configuration
    .GetSection("ElasticSearch")
    .Get<Dictionary<string,object>>();
string json = JsonConvert.SerializeObject(settings);
like image 108
chris31389 Avatar answered Oct 11 '22 02:10

chris31389


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"];
like image 41
Babak Naffas Avatar answered Oct 11 '22 02:10

Babak Naffas