Search code examples
c#json.net-core-2.2

C# ConfigurationBuilder Get JsonObject


I have a Problem accessing the values of a JSON config file with the Configuration Builder My JSON Looks like that

{
  "item": [
    {
      "valueType": "taktzeit",
      "interval": 3
    },
    {
      "valueType": "werkzeugwechsel",
      "interval": 5
    }
  ]
}

Update It is in a folder called Config --> Config/config.json . I set the property, so the file is in the build folder

My Code:

var a = builder.AddJsonFile(Globals.ConfigPath).Build()
                .GetSection("item").GetChildren().ToList().Select(x => x.Value).ToList();

This is what I get when I loop through "a"'

enter image description here

Don´t see what I am missing. Thanks in advance

Update 2

My Model:

public class Config
{
        public List<Item> Item { get; set; }
}

public class Item
{
    public string ValueType { get; set; }
    public int Interval { get; set; }
}

Solution

  • Change This

    var a = builder.AddJsonFile(Globals.ConfigPath).Build()
                .GetSection("item").GetChildren().ToList().Select(x => x.Value).ToList();
    

    to

    var a = builder.AddJsonFile(Globals.ConfigPath).Build()
                .GetSection("item").Get<List<Item>>();
    

    this will result list of Item