1

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; }
}
7
  • what is the name of the Jason file in project ? Is it appsettings.json file ? Commented Nov 19, 2019 at 15:19
  • No, its a file in a folder: Config/config.json. I already set the file to be in the build. If I use....GetSection("item:0:valuteTyp").. I get whats inside the file. But I need it in a more generic way Commented Nov 19, 2019 at 15:26
  • Can we see the class that this is deserializing to? It seems you have "x.Value" in your LINQ, but "valueType" in your JSON. Commented Nov 19, 2019 at 15:26
  • I updated my post Commented Nov 19, 2019 at 15:30
  • 1
    try this var a = builder.AddJsonFile(Globals.ConfigPath).Build() .GetSection("item").Get<List<Item>>(); see if it return list f Item Commented Nov 19, 2019 at 15:43

2 Answers 2

2

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

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

Comments

0

Assuming all else is already configured, simply bind to the desired object graph.

IConfiguration configuration = new ConfigurationBuilder()
                                    .AddJsonFile(Globals.ConfigPath)
                                    .Build();

Config config = configuration.Get<Config>();

Reference Configuration in ASP.NET Core

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.