c# - 如何从 appsettings.json 文件中的对象数组读取值

标签 c# arrays object configuration appsettings

我的应用程序设置 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);
}

Try it online

关于c# - 如何从 appsettings.json 文件中的对象数组读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69308734/

相关文章:

c# - 如何在 XAML 中为自定义 DataGrid 控件指定 GroupDescriptions?

c# - 如何使用 Eval 减去两列

javascript - 如何通过单击按钮清除 javascript 中数组的内容?

javascript - 比较 2 个嵌套数组以返回重复数组

javascript - 如何在本地存储中保存对象、变量、数组?

java - 如何使用对象作为类的变量,如ArrayList?

JavaScript 对象文字不起作用

javascript - Google Apps 脚本在 Google 表格中进行多个查找和替换正则表达式

c# - C# 中十进制类型的解析意外失败

c# - 如何更改 MetroComboBox 中的默认选择项?