如何用值列表读取 appsettings.json?
How to read appsettings.json with List of values?
我有以下 appSettings.json 文件
"UrlManagement": {
"UrlList": [
{
"Microsoft":{
"resource":"xyz",
type": "iot"
},
"AWS":{
"resource":"abc",
"type": "storage"
},
}]
}
}
我有class
public class UrlManagement
{
public string CompanyName;
public URLList UrlList;
}
public class URLList
{
public string Resource;
public string Type;
}
我正在尝试获取这些值,如下所示
private List<string> GetConfigurationDictionary()
{
var items = this._configuration.GetSection("UrlManagement:UrlList:0").
GetChildren().ToDictionary(x => x.Key, x => x.Value);
}
我得到 x.Value
的空值
您可以搜索UrlManagement:UrlList:0
部分,如以下代码:
private List<UrlManagement> GetConfigurationDictionary()
{
List<UrlManagement> result = this._configuration
.GetSection("UrlManagement:UrlList:0")
.GetChildren()
.ToDictionary(x => x.Key, x => x.Get<UrlList>())
.Select(x => new UrlManagement { CompanyName = x.Key, UrlList = x.Value })
.ToList();
return result;
}
演示
foreach (var item in result)
{
Console.WriteLine($"{item.CompanyName} ==> {item.UrlList.Type}:{item.UrlList.Resource}");
}
结果
AWS ==> storage:abc
Microsoft ==> iot:xyz
我希望这可以帮助您解决问题
我有以下 appSettings.json 文件
"UrlManagement": {
"UrlList": [
{
"Microsoft":{
"resource":"xyz",
type": "iot"
},
"AWS":{
"resource":"abc",
"type": "storage"
},
}]
}
}
我有class
public class UrlManagement
{
public string CompanyName;
public URLList UrlList;
}
public class URLList
{
public string Resource;
public string Type;
}
我正在尝试获取这些值,如下所示
private List<string> GetConfigurationDictionary()
{
var items = this._configuration.GetSection("UrlManagement:UrlList:0").
GetChildren().ToDictionary(x => x.Key, x => x.Value);
}
我得到 x.Value
的空值您可以搜索UrlManagement:UrlList:0
部分,如以下代码:
private List<UrlManagement> GetConfigurationDictionary()
{
List<UrlManagement> result = this._configuration
.GetSection("UrlManagement:UrlList:0")
.GetChildren()
.ToDictionary(x => x.Key, x => x.Get<UrlList>())
.Select(x => new UrlManagement { CompanyName = x.Key, UrlList = x.Value })
.ToList();
return result;
}
演示
foreach (var item in result)
{
Console.WriteLine($"{item.CompanyName} ==> {item.UrlList.Type}:{item.UrlList.Resource}");
}
结果
AWS ==> storage:abc
Microsoft ==> iot:xyz
我希望这可以帮助您解决问题