Reputation: 1490
My configuration file looks like:
"app": {
"Token": "sfasgeagesagasdgdas",
"Address": "https://localhost",
"User": "me",
"Password": "pwd123",
"Users": [
{
"Id": "123456",
"Username": "me"
},
{
"Id": "234567",
"Username": "notme"
}
]
}
I can get the token and address by:
Configuration["app:Token"];
But this approach does not work with json array values. How should I use json array?
Upvotes: 0
Views: 187
Reputation: 21353
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:
Upvotes: 2
Reputation: 1274
You should read that like this in NET5:
var user0_id = config["app:Users:0:Id"];
var user1_id = config["app:Users:1:Id"];
var user0_username = config["app:Users:0:Username"];
Upvotes: 0