Asp.Net Core Get Json Array Using Iconfiguration

.NetCore - Get Arrays from JSON file

I gave singleton dependency to configuration in the startup class and this worked.
that was the problem. i just modified my code in which first get all the keys (arrays) and then in the foreach loop i am getting the array's value by the key it gets one by one.

public Dictionary<string, List<string>> GetSettings()
{
var response = new Dictionary<string, List<string>>();
var settings = Configuration.GetSection("Settings").GetChildren().Select(x => x.Key).ToList();
foreach (var setting in settings)
{
response.Add(setting, Configuration.GetSection($"Settings:{setting}").Get<List<string>>());
}
return response;
}

Asp.Net Core get json array from appsettings.json

The GetChildren() method will return you IEnumerable<IConfigurationSection>, which is great if working with simple types such as a list of strings. For instance:

{
"EndPointUsernames": [
"TestUser1",
"TestUser2",
"TestUser3",
"TestUser4"
]
}

can easily be added to a string array without the need to define a separate class such as EndPointConfiguration as you have. From here you could simply call

string[] userNames = Configuration.GetSection("EndPointUsernames").GetChildren().ToArray().Select(c => c.Value).ToArray();

to retrieve these values. You've done it correctly in your example as you've strongly typed the results to a list of EndPointConfiguration objects.

ASP.NET core read array from applicationsettings.json

From your description, you want to get the Users information.

If you want to get the special user, you could use the following code (change the item index):

var user1_id = Configuration["app:Users:1:Id"];
var user1_username = Configuration["app:Users:1:Username"];

If you want to get all value of the entire array, you could use the following code:

IConfigurationSection myArraySection = Configuration.GetSection("app").GetSection("Users");
var itemArray = myArraySection.AsEnumerable();

Besides, if you could also create a Users Model base on the Json array:

public class Users
{
public string Id { get; set; }
public string Username { get; set; }
}

Then, use the following code to get the user data:

List<Users> myTestUsers = Configuration.GetSection("app").GetSection("Users").Get<List<Users>>();

The result like this:

Sample Image

Read configuration List from appsettings.json

I saw this reply on Stackoverflow that is exactly the same issue I have. The solution is the following:

SmtpCredentialsSettings[] smtpCredentials = 
Configuration.GetSection("SmtpCredentials")
.Get<SmtpCredentialsSettings[]>();
services.Configure<SmtpSettings>(option =>
{
option.SmtpCredentials = smtpCredentials;
});
services.AddScoped(cfg => cfg.GetService<IOptions<SmtpSettings>>().Value);


Related Topics



Leave a reply



Submit