0

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?

3

2 Answers 2

2

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:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

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"];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.