我的应用程序设置 json 文件
{
"StudentBirthdays": [
{ "Anne": "01/11/2000"},
{ "Peter": "29/07/2001"},
{ "Jane": "15/10/2001"},
{ "John": "Not Mentioned"}
]
}
我有一个单独的配置类。
public string GetConfigValue(string key)
{
var value = _configuration["AppSettings:" + key];
return !string.IsNullOrEmpty(value) ? Convert.ToString(value) : string.Empty;
}
我尝试过的是,
list= _configHelper.GetConfigValue("StudentBirthdays");
对于上述内容,我没有得到值。
如何读取这些值(我想分别读取学生的姓名和生日)。
感谢任何帮助
最佳答案
您可以使用以下代码获取生日:
// get the section that holds the birthdays
var studentBirthdaysSection = _configuration.GetSection("StudentBirthdays");
// iterate through each child object of StudentBirthdays
foreach (var studentBirthdayObject in studentBirthdaysSection.GetChildren())
{
// your format is a bit weird here where each birthday is a key:value pair,
// rather than something like { "name": "Anne", "birthday": "01/11/2000" }
// so we need to get the children and take the first one
var kv = studentBirthdayObject.GetChildren().First();
string studentName = kv.Key;
string studentBirthday = kv.Value;
Console.WriteLine("{0} - {1}", studentName, studentBirthday);
}
关于c# - 如何从 appsettings.json 文件中的对象数组读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69308734/