Home > Software engineering >  Arrays of un-named json tuple in appsettings.json
Arrays of un-named json tuple in appsettings.json

Time:10-05

In appsettings.json I have unnamed json:

{
    "Items": [
        {"Item1": "Content1"},
        {"Item2": "Content2"}
    ]
}

Now I want it in a variable and I'm looking for direct simple code like:

public static readonly IConfiguration config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
...
(string,string)[] items = config.GetValue<(string,string)[]>("Items");

What would be a simple solution since the line above doesn't work. I'm looking for something that would replace this part: "config.GetValue<(string,string)[]>("Items");"

Tried those:

(string,string)[] items = config.GetSection("Items")
  .GetChildren()
  .ToList()
  .Select(x => (x.Key,x.Value)).ToArray();
Console.WriteLine($"{items.Length}, {items[1]}"); // 2, (1, )
var items = config.GetValue<List<Dictionary<string,string>>>("Items"); // null

var items = config.GetValue<List<Tuple<string,string>>>("Items"); // null

var items = config.GetValue<List<KeyValuePair<string,string>>>("Items"); // null

CodePudding user response:

Use Configuration.GetSection(string) to obtain the value corresponding to the Items key first & then construct an IEnumerable<Tuple<string,string>> from the children values.

ConfigurationSection section = config.GetSection("Items");

var data = section
.GetChildren()
.Select(x => new Tuple<string, string>(x.Key, x.Value));

CodePudding user response:

To do what you want you can use the "Bind" method like this:

    private List<T> GetList<T>(string configSection)
    {
        var result = new List<T>();
        config.GetSection($"{configSection}").Bind(result);
        return result;
    }

You can call this method like this

GetList<Dictionary<string, string>>("Items");

You need to reference nuget Microsoft.Extensions.Configuration.Binder

Notice I wrapped the logic into a method... But you can just use the code directly without wrapping a method like this:

        var items= new List<Dictionary<string,string>>();
        config.GetSection("Items").Bind(result);

Now what you get is a List of Dictionaries. But it is because of the "shape" of your JSON.

It can be simplified to a single dictionary like this:

{
    "Items":  {
           "Item1": "Content1",
           "Item2": "Content2"
        }    
}

and then calling this code:

        var items= new Dictionary<string, string>();
        config.GetSection("Items").Bind(result);

In my opinion the last option in which you get single dictionary is better and more scalable.

  • Related