Home > OS >  How to read values from array of objects in appsettings.json file(c#)
How to read values from array of objects in appsettings.json file(c#)

Time:09-24

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: Create Model/Class like below: public class StudentBirthday { String Name, String Birthday }

Then access values like this : List StudentBirthdays = _config.GetSection("Main:StudentBirthdays").Get<List>();

CodePudding user response:

try this

var json=...your json;

var jD = JsonConvert.DeserializeObject<Data>(json);
var items= jD.StudentBirthdays.SelectMany(i=> i).ToList();
foreach (var item in items) Console.WriteLine($"Name: {item.Key} , DOB: {item.Value} ");

public class Data
{
    public Dictionary<string, string>[] StudentBirthdays { get; set; }
}

result

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

  • Related