Liana
Liana

Reputation: 45

Asp.Net Core get json array from appsettings.json

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.

Upvotes: 2

Views: 1322

Answers (1)

Misanthropist
Misanthropist

Reputation: 211

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.

Upvotes: 2

Related Questions