Home > Software design >  How to read sub array of values from appsetting.json using IConfiguration?
How to read sub array of values from appsetting.json using IConfiguration?

Time:02-25

What I need is to get the GroupAssets SearchPath value by matching the Name value to a value from a database query. At this point I am just trying to pull the GroupAssets into an array.

appsettings.json

"Production": {
    "PrintJobs": [
      {
        "SalesCategory": "5084",
        "JobType": 1,
        "SubJobType": 5014,
        "ShipVia": 5019,
        "CSR": 360,
        "SLAHours": 216,
        "DaysToArrive": 5,
        "Note": [ "" ],

        "GroupAssets": [
          {
            "Name": "MapImage",
            "SearchPath": "\\\\Server\\Path",
            "PrintAssetType": "Image",
            "ValidExtensions": [ "jpg" ]
          },
          {
            "Name": "PageImage",
            "SearchPath": "\\\\Server\\Path",
            "PrintAssetType": "Image",
            "ValidExtensions": [ "jpg" ],
            "CreativeCodes": [ "M1YV", "M1YW" ]
          },
          {
            "Name": "ItineraryPage",
            "SearchPath": "\\\\Server\\Path",
            "PrintAssetType": "Pdf",
            "ValidExtensions": [ "pdf" ],
            "CreativeCodes": [ "M1YV", "M1YW" ]
          }

        ],
     }
}

My code:

var myArray = _config.GetSection("Production:PrintJobs").GetChildren();

public class PrintAssetDefns
{
   public string Name { get; set; }
   public string SearchPath { get; set; }
   public string PrintAssetType { get; set; }
   public string ValidExtensions { get; set; }
   public string CreativeCodes { get; set; }
}

CodePudding user response:

try this

PrintAssetDefns[] MyArray = configuration.GetSection("Production:PrintJobs")
.GetChildren().First().GetSection("GroupAssets").Get<PrintAssetDefns[]>();

or you can get all data

PrintJob[] myArray = _config.GetSection("Production:PrintJobs").Get<PrintJob[]>();

classes

public class PrintAssetDefns
{
    public string Name { get; set; }
    public string SearchPath { get; set; }
    public string PrintAssetType { get; set; }
    public List<string> ValidExtensions { get; set; }
    public List<string> CreativeCodes { get; set; }
}

public class PrintJob
{
    public string SalesCategory { get; set; }
    public int JobType { get; set; }
    public int SubJobType { get; set; }
    public int ShipVia { get; set; }
    public int CSR { get; set; }
    public int SLAHours { get; set; }
    public int DaysToArrive { get; set; }
    public List<string> Note { get; set; }
    public List<PrintAssetDefns> GroupAssets { get; set; }
}

  • Related