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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With