【发布时间】:2018-08-02 16:43:41
【问题描述】:
TL;DR:如何从 appsettings.json 读取复杂的 JSON 对象?
我有一个具有多种配置值类型的 .NET Core 2.x 应用程序。 appsettings.json 看起来像下面的 sn-p,我正在尝试将 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") 毫无问题地读取简单的配置值(键:值对)。
Configuration.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") 也返回一个空值。出于与上述相同的原因,这对我来说也很有意义。
【问题讨论】:
-
这只是一个错字吗?您的密钥中有一个双
::... -
@DavidG 是的,这是我的示例中的一种类型,在我的代码中没有出现。现在修复它。
-
另外,您不能在复杂对象上调用
.Value,这仅适用于string值。 -
我正在尝试任何我能想到的东西,看看它是否会起作用或帮助我找出其他解决方案。我已经能够通过将 appsettings.json 作为 JSON 文件读取并获取我需要的对象来使其工作。
-
我可以通过直接解析
appsettings.json并读取我需要的属性来解决问题。但我还是想看看有没有其他选择。
标签: json .net-core configuration-files