【问题标题】:How to read sub array of values from appsetting.json using IConfiguration?如何使用 IConfiguration 从 appsetting.json 读取值的子数组?
【发布时间】:2022-02-25 03:29:31
【问题描述】:

我需要通过将 Name 值与数据库查询中的值匹配来获取 GroupAssets SearchPath 值。此时我只是想将 GroupAssets 拉到一个数组中。

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" ]
          }

        ],
     }
}

我的代码:

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; }
}

【问题讨论】:

    标签: c# asp.net-core


    【解决方案1】:

    试试这个

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

    或者你可以获取所有数据

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

    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; }
    }
    
    

    【讨论】:

    • 这无疑增加了另一个需要考虑的途径。谢谢!
    猜你喜欢
    • 2020-08-14
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    • 2019-02-16
    • 1970-01-01
    • 2018-12-18
    相关资源
    最近更新 更多