我在 .NET Core 控制台应用程序中有以下 appsettings.json。 Options pattern 上显示的示例页面不包含复杂类型的应用程序设置。
如何在以下应用设置中循环访问每种报告类型的列?
{
"Reports": [
{
"name": "Roles",
"fileName": "roles.csv",
"columns": [
{
"name": "ROLE_ID",
"default": ""
},
{
"name": "NAME",
"default": ""
},
{
"name": "AVAILABILITY_IND",
"default": "YES"
}
]
},
{
"name": "Accounts",
"fileName": "accounts.csv",
"columns": [
{
"name": "ROLE",
"default": "NONE"
},
{
"name": "USER_ID",
"default": ""
},
{
"name": "LASTNAME",
"default": ""
},
{
"name": "FIRSTNAME",
"default": ""
}
]
}
]
}
最佳答案
您可以像下面那样读取嵌套数组:
public class HomeController : Controller
{
private readonly IConfiguration _configuration;
public HomeController(IConfiguration configuration)
{
_configuration = configuration;
}
public IActionResult Index()
{
//read the first report's columns array's first item's name------"ROLE_ID"
var data = _configuration.GetSection("Reports:0:columns:0:name");
return View();
}
关于如何foreach所有键和值:
var model = _configuration.GetSection("Reports").AsEnumerable();
foreach (var kv in model)
{
Console.WriteLine("{0}: {1}", kv.Key, kv.Value);
}
您可以也反序列化 json 以建模并从模型中获取项目:
型号:
public class Rootobject
{
public Report[] Reports { get; set; }
}
public class Report
{
public string name { get; set; }
public string fileName { get; set; }
public Column[] columns { get; set; }
}
public class Column
{
public string name { get; set; }
public string _default { get; set; }
}
Controller :
var json = System.IO.File.ReadAllText("yourJsonfile.json");
var DeserializeModel = JsonSerializer.Deserialize<Rootobject>(json);
注意事项:
如果您的 json 文件不是默认的 appsettings.json
。有些像:test.json
等。并且您还想从 IConfiguration 中读取它,您需要记住在 Startup.cs 中注册:
public class Startup
{
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
configuration = new ConfigurationBuilder().SetBasePath(env.ContentRootPath)
.AddJsonFile("test.json")
.Build();
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddSingleton<IConfiguration>(Configuration);
}
}
关于c# - 如何为 appsettings.json 复杂数组使用选项模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66035950/