json - 从appsettings.json读取JSON对象

标签 json .net-core configuration-files

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")来读取简单的配置值(键:值对),而不会出现问题。

配置。GetSectionConfiguration.GetSection("ElasticSearch:MyIndex:mappings").Value给我nullValue值。

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/

相关文章:

Python3.5 对象和 json.dumps() 输出

entity-framework - EF Core Second level ThenInclude misworks

javascript - Greasemonkey 脚本中的配置文件

mysql - JSON_Search() 返回 null

json - 以不区分大小写的方式使用 json_populate_recordset

asp.net-core - 将 JwtBearerOptions 注入(inject) Controller

c# - 在 C# 中,我可以从方法而不是 lambda 创建表达式树对象吗?

view - 是否可以在操作中从 view.yml 获取值

c++ - 如何制作一个可以处理 .txt 文件而不显示它的 C++ 程序

arrays - PostgreSQL 将出现次数计入 json 键/值