2

I met a problem when retrieving the json array set in appsettings.json.

When using Configuration.GetSection("xxx").GetChildren() to get json array, and the return value is null. Then I used the way below to solve the problem, and it worked.

In appsettings.json:

{
  "EndPointConfiguration": [
    {
      "UserName": "TestUser",
      "Email": "[email protected]"
    },
    {
      "UserName": "TestUser",
      "Email": "[email protected]"
    }
  ]
}

Then I create the class:

public class EndPointConfiguration 
{
    public string UserName { get; set; }
    public string Email { get; set; }
}

Finally, using an array of the EndPointConfiguration class will work:

var endPointConfiguration = Configuration.GetSection("EndPointConfiguration").Get<EndPointConfiguration[]>();

I am pretty new to .net core, do not why the Configuration.GetSection().GetChildren() cannot work. Can anyone proficient help to give an answer? Thanks.

1
  • getChildren returns a list of IConfigurationSection which is a section defined by a key and having a value(docs). An array of objects is not a IConfigurationSection as it does not contain a string key to be referenced Commented May 7, 2019 at 13:30

1 Answer 1

2

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.

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

1 Comment

Thank you so much for explaining!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.