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

ris*_*ssa 3 c# arrays configuration object appsettings

我的 appsettings json 文件

       {
         "StudentBirthdays": [
                { "Anne": "01/11/2000"},
                { "Peter": "29/07/2001"},
                { "Jane": "15/10/2001"},
                { "John": "Not Mentioned"}
            ]
        }
Run Code Online (Sandbox Code Playgroud)

我有一个单独的配置类。

public string GetConfigValue(string key)
{
    var value = _configuration["AppSettings:" + key];
    return !string.IsNullOrEmpty(value) ? Convert.ToString(value) : string.Empty;
}
Run Code Online (Sandbox Code Playgroud)

我尝试过的是,

 list= _configHelper.GetConfigValue("StudentBirthdays");
Run Code Online (Sandbox Code Playgroud)

对于上述内容,我没有得到这些值。

我如何读取这些值(我想分别读取学生的姓名和他的生日)。

任何帮助表示赞赏

Joh*_*ica 5

您可以使用以下代码获取生日:

// 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);
}
Run Code Online (Sandbox Code Playgroud)

在线尝试一下