50

I have a .NET Core console application and want to read the appsettings.json and parse a section as List<Param> (without Dependency Injection or ASP.NET Core).
I already tried How do I bind a multi level configuration object using IConfiguration in a .net Core application? but it seems like .Get<T>() got removed from netcoreapp1.1

IConfigurationSection myListConfigSection = configurationRoot.GetSection("ListA");

List<Param> paramList;

//Get does not exist
//paramList = myListConfigSection.Get<Param>();

string paramListJson = myListConfigSection.Value // is null
// won't work neither because paramListJson is null
paramList = JsonConvert.DeserializeObject<Param>(paramListJson);

appsettings.json:

{
  "ListA": [
    { "ID": "123", "Param": "ABC"},
    { "ID": "123", "Param": "JKS"},
    { "ID": "456", "Param": "DEF"}
  ]
}

Is there an easy way to load the config into the object or do I have to read the config file again and parse it myself with JsonConvert?

1

2 Answers 2

121

Get<T> is defined in package Microsoft.Extensions.Configuration.Binder

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

4 Comments

Thanks, it did the trick. As much I love it, I sometimes hate that they switched everything to a different nkpg.
#loveHate Yep,I'm always searching for and finding that "extra" nkpg.
This doesn't appear to be the same as GetSection as it appears to get the entire config file as an object.
You can use it an on IConfiguratoinSection and get just this section as an object
0

Microsoft.Extensions.Configuration.Binder isnt really required as long as you are using primitive types to define the leaf properties. Once your type has collections such as List / IEnumerable, you will require Binder.

However, if your code defines a collection as array, it would work just fine without the need for Binder.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.