Home > Back-end >  How to read values from array of objects in appsettings.json file
How to read values from array of objects in appsettings.json file

Time:09-27

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

CodePudding user response:

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

CodePudding user response:

try this

using System.Linq;

public List<Student> GetStudentsFromConfig()
{
    return  _configuration
    .GetSection("StudentBirthdays")
    .Get<Dictionary<string, string>[]>()
    .SelectMany(i => i)
    .Select(ie => new Student {Name=ie.Key, DOB=ie.Value})
    .ToList();
}

test

items= _configHelper.GetStudentsFromConfig();

foreach (var item in items) Console.WriteLine($"Name: {item.Name} , DOB: {item.DOB} ");

result

Name: Anne , DOB: 01/11/2000 
Name: Peter , DOB: 29/07/2001 
Name: Jane , DOB: 15/10/2001 
Name: John , DOB: Not Mentioned 

class

public class Student
{
    public string Name { get; set; }
    public string DOB { get; set; }
}

CodePudding user response:

Try this: Create Model/Class like below:

public class StudentBirthday
{
   String Name,
   String Birthday
}

Then access values like this :

List<StudentBirthday StudentBirthdays = 
   _config.GetSection("Main:StudentBirthdays").Get<List<StudentBirthday();
  • Related