0

I have a string in appsettings.json:

    {
  "GeneralSettings": {
    "CompanyIds": "1,2,3,4,5"
  }
}

How can I map it to a class, I need split it into the list by comma:

public class GeneralSettings
{
    public List<int> CompanyIds { get; set; }
}

Now I have:

var generalSettings = new GeneralSettings();  
configuration.GetSection(nameof(GeneralSettings)).Bind(generalSettings);
MrChudz
  • 909
  • 3
  • 10
  • 17
  • 1
    Why is it a string, and not an array? See also https://stackoverflow.com/questions/61203218/asp-net-core-custom-converter-appsettings-json-for-idictionarystring-object if you must parse it yourself, then do so. – CodeCaster Feb 24 '21 at 10:16
  • a good idea!! Thx – MrChudz Feb 24 '21 at 11:39

2 Answers2

3

Can't you just have an array in your config file ?

{
  "GeneralSettings": {
    "CompanyIds": [1,2,3,4,5]
  }
}
Arcord
  • 1,724
  • 1
  • 11
  • 16
1

you can use this code :

 var generalSettings = new GeneralSettings(); 
 var values = _configuration.GetSection(nameof(GeneralSettings) +   ":CompanyIds").Value;
 generalSettings.CompanyIds  = values.Split(",").ToList().ConvertAll(int.Parse);

or

generalSettings.CompanyIds =  values.Split(",").Select(c=>int.Parse(c)).ToList();
Sign
  • 113
  • 8