c# - 如何为 appsettings.json 复杂数组使用选项模式
问题描述
我在 .NET Core 控制台应用程序中有以下 appsettings.json。此选项模式页面上显示的示例不涵盖复杂类型的应用程序设置。
如何遍历以下应用设置中每种报告类型的列?
{
"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();
}
对于如何获取所有键和值:
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; }
}
控制器:
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);
}
}
推荐阅读
- flutter - 如何在颤动中返回前2页
- javascript - 自动更改图像的轮播 [JS]
- c - 在 C 语言中,我可以使用 `<` 或 `>` 来比较指向 NULL 的指针吗?
- gnuplot - 使用 GNU Plot 绘图,标题基于列名
- autodesk-forge - Autodesk Forge - 捕获问题位置的图像
- git - 为什么我不能推送到heroku?
- php - Laravel:从Json数据中获取邮递员测试的用户ID为空
- ios - 如何在 Swift 中测试和模拟属性包装器?
- javascript - 控制台中的 JavaScript 错误 - 模态窗口
- python - 是否可以将 Azure 事件中心接收器与 Flask 集成并在 Flask 中接收数据?