How to read nested objects from appsettings?

84 views Asked by At

In my .NET Core application, I am trying to read data from appsettings.json.

I have this configuration in appsettings.json:

"ServiceDetails": {
   "CellDetails": {
     "ScenarioName": [ 4, 5 ],
     "ServiceName": [ 5, 5 ]
   }
}

I would like to read this and convert into list like this:

scenario name, 4,5
service name, 5,5

Model class for the above list:

public class CellDetails
{
     public string CellKeyValue { get; set; }
     public int Row { get; set; }
     public int Column { get; set; }
}

I am trying something like this

var serverUrl = configuration.GetSection("ServiceDetails")
                     .GetSection("CellDetails").Get<string[]>();

Above code doesn't work, can someone help me to fix this? Any help would be appreciated.

2

There are 2 answers

3
Qing Guo On BEST ANSWER

Do you want this?

var myArray = configuration.GetSection("ServiceDetails:CellDetails:ScenarioName").Get<int[]>();

result: enter image description here

Update:

Try to create a model ServiceDetails like:

public class ServiceDetails
{
    public List<CellDetails> CellDetails { get; set; }
}

Then in appsettings.json :

"ServiceDetails": {
  "CellDetails": [
    {
      "CellKeyValue": "ScenarioName",
      "Row": 4,
      "Column": 5
    },
    {
      "CellKeyValue": "ServiceName",
      "Row": 5,
      "Column": 5
    }
  ]
}

Then

var myArray = configuration.GetSection("ServiceDetails:CellDetails").Get<List<CellDetails>>() ;

result: enter image description here

0
Amir Elsagan On

It's not Recommended way do this, but if you don't change the schema this will be helpful:

var arr = builder.Configuration.GetSection("ServiceDetails:CellDetails").GetChildren();

foreach (var item in arr)
{
    Console.WriteLine(item.Key + " : "+ item.GetSection("0").Value + ", "+ item.GetSection("1").Value);
}

And this is the output:

output