Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read values from array of objects in appsettings.json file

My appsettings json file

       {
         "StudentBirthdays": [
                { "Anne": "01/11/2000"},
                { "Peter": "29/07/2001"},
                { "Jane": "15/10/2001"},
                { "John": "Not Mentioned"}
            ]
        }

I have a seperate config class.

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

What I have tried is,

 list= _configHelper.GetConfigValue("StudentBirthdays");

For the above I dont get the values.

How can I read the values(I want to read the name of the student and his birthday seperatly).

Any help is apreciated

like image 586
rissa Avatar asked Oct 18 '25 07:10

rissa


1 Answers

You can obtain the birthdays using the following code:

// 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

like image 109
DiplomacyNotWar Avatar answered Oct 19 '25 21:10

DiplomacyNotWar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!