0

I create some config file in json format:

{
    "SomeCollection" : [
        {
            "Val1" : "Some string",
            "Val2" : "Some string2"
        }
    ] 
}

I create object with this config:

IConfiguration config = new ConfigurationBuilder()
      .AddJsonFile("appsettings.json", true, true)
      .Build();

But how can I get list of pairs Val1 and Val2?

ekad
  • 14,436
  • 26
  • 44
  • 46
lgabryel
  • 109
  • 1
  • 9
  • ```var section = config.GetSection("SomeCollection"); var val1 = section.GetValue("Val1");``` – Paul Feb 01 '19 at 10:40
  • Ok, but in file may be n time Val1, Val2 object. You understand me? – lgabryel Feb 01 '19 at 10:43
  • @Igabryel use GetSection as string and deserialize using the json – prisar Feb 01 '19 at 10:44
  • Can you give me some example? – lgabryel Feb 01 '19 at 11:15
  • you can convert section to class direcly with : ```var section = config.GetSection("SomeCollection") as YourCustomClass;``` Define a class with dictionnary in it and you can get it. Or you can try ```JsonConvert.DeserializeObject(config.GetSection("SomeCollection").ToString());``` – Paul Feb 01 '19 at 11:20

2 Answers2

1

This is my class:

using System.Collections.Generic;

namespace WebsiteAPI.Models
{
   public class CollectionInAppSettings
   {
        public IDictionary<string,string> SomeCollection { get; set; }
   }
}

This is my AppSettings:

"CollectionInAppSettings": {
    "SomeCollection": {
        "Val1": "Some string",
        "Val2": "Some string2"
    }
}

This is what is in my startup.cs in the ConfigureServices Section:

services.Configure<CollectionInAppSettings>(Configuration.GetSection("CollectionInAppSettings"));

This is whats in a dummy HelloController:

    private readonly IOptions<CollectionInAppSettings> _options;

    public HelloController(IOptions<CollectionInAppSettings> options)
    {
        _options = options;
    }

    [HttpGet("[action]")]
    public IActionResult IsUp()
    {
        return Ok(_options.Value);
    }

When calling the endpoint: https://localhost:4010/api/hello/isup

This is returned: "someCollection":{"Val1":"Some string","Val2":"Some string2"}

Here is a link to some other solutions to this problem: Click here

HenryMigo
  • 164
  • 1
  • 7
0

Ok folks. After a few experiments, I get a solution!

IConfiguration config = new ConfigurationBuilder()
  .AddJsonFile("appsettings.json", true, true)
  .Build();
foreach( var en in config.GetSection("SomeCollection").GetChildren())
{
  string Val1= en["Val1"];
  string Val2= en["Val2"];
}

Thank for trying help!

lgabryel
  • 109
  • 1
  • 9
  • You should use `IOptions` as suggested by HenryMigo. This is definitely *not* the recommended method (and your JSON is not correctly structured) – iCollect.it Ltd Feb 11 '19 at 09:15