How to extract a list from appsettings.json in .net core

I have an appsettings.json file which looks like this:

{
    "someSetting": {
        "subSettings": [
            "one",
            "two",
            "three"
         ]
    }
}

When I build my configuration root, and do something like config["someSetting:subSettings"] it returns null and the actual settings available are something like this:

config["someSettings:subSettings:0"]

Is there a better way of retrieving the contents of someSettings:subSettings as a list?


Solution 1:

Assuming your appsettings.json looks like this:

{
  "foo": {
    "bar": [
      "1",
      "2",
      "3"
    ]
  }
}

You can extract the list items like so:

Configuration.GetSection("foo:bar").Get<List<string>>()

Solution 2:

You can use the Configuration binder to get a strong type representation of the configuration sources.

This is an example from a test that I wrote before, hope it helps:

    [Fact]
    public void BindList()
    {
        var input = new Dictionary<string, string>
        {
            {"StringList:0", "val0"},
            {"StringList:1", "val1"},
            {"StringList:2", "val2"},
            {"StringList:x", "valx"}
        };

        var configurationBuilder = new ConfigurationBuilder();
        configurationBuilder.AddInMemoryCollection(input);
        var config = configurationBuilder.Build();

        var list = new List<string>();
        config.GetSection("StringList").Bind(list);

        Assert.Equal(4, list.Count);

        Assert.Equal("val0", list[0]);
        Assert.Equal("val1", list[1]);
        Assert.Equal("val2", list[2]);
        Assert.Equal("valx", list[3]);
    }

The important part is the call to Bind.

The test and more examples are on GitHub