Search code examples
c#jsonappsettingsasp.net-core-configuration

How to traverse the properties in the appSettings class, with configuration from appSettings.json


I have an appSettings.json file with the following group:

"Devices": {
  "_850347_74Crompton1": "3605",
  "_850532_41Crompton2": "813",
  "_850722_18IMEElectricity": "707",
  "_850766_85DustNoise1": "306",
  "_850772_63Dustnoise2": "2866",
  "_850774_29DustNoise3": "3104",
  "_863859_63Level": "22601",
  "_864233_30": "713",
  "_864319_07noise": "606"
}

My Devices class is:

public class Devices
{
    public string _850347_74Crompton1 { get; set; }
    public string _850532_41Crompton2 { get; set; }
    public string _850722_18IMEElectricity { get; set; }
    public string _850766_85DustNoise1 { get; set; }
    public string _850772_63Dustnoise2 { get; set; }
    public string _850774_29DustNoise3 { get; set; }
    public string _863859_63Level { get; set; }
    public string _864233_30 { get; set; }
    public string _864319_07noise { get; set; }
}

I can easily get to the values in this object, using something like:

var myDevice = config.GetRequiredSection("Devices").Get<Devices>();

And refer to a value of my choice, for example:

var myValue = myDevice._850347_74Crompton1;
var anotherValue = myDevice._864233_30;

But I don't want to hardcode it like this. I want to traverse the list (properties), using something like this:

foreach (Devices d in Devices)
{
   myDevice = d.Key;
   myDeviceValue = d.Value;
}

I just can't see to get it to work. No errors, just getting nulls or not "formed" properly type code.

Thanks.

UPDATE

I've tried this, but I get an error.

Devices iot = config.GetRequiredSection("Devices").Get<Devices>();

foreach (Devices device in iot)
{
   ...
}

Severity Code Description Project File Line Suppression State Error CS1579 foreach statement cannot operate on variables of type 'appSettings.Devices' because 'appSettings.Devices' does not contain a public instance or extension definition for 'GetEnumerator' IoT_CaptisDataCapture .....\Program.cs 60 Active


Solution

  • Read the JSON as Dictionary<string, string>.

    var myDevice = config.GetRequiredSection("Devices").Get<Dictionary<string, string>>();
    
    foreach (KeyValuePair<string, string> kvp in myDevice)
    {
        Console.WriteLine($"{kvp.Key}: {kvp.Value}");
    }