如何读取appsettings.json文件中对象数组内的学生姓名和生日
问题根因
- 现有
GetConfigValue方法仅支持读取字符串类型的单值配置,无法直接解析数组/对象结构的配置 - 方法硬编码了
AppSettings:前缀,但你的StudentBirthdays节点直接位于配置根层级,路径不匹配导致读取失败
实现方案
方案1:扩展工具类做强类型绑定(推荐)
这种方式代码可维护性更高,适合配置结构固定的场景
- 如果你可以调整appsettings.json的结构,更推荐改成下面的规范结构,强类型绑定更方便:
{ "StudentBirthdays": [ { "Name": "Anne", "Birthday": "01/11/2000"}, { "Name": "Peter", "Birthday": "29/07/2001"}, { "Name": "Jane", "Birthday": "15/10/2001"}, { "Name": "John", "Birthday": "Not Mentioned"} ] }
然后定义对应的配置实体类:
public class StudentBirthdayItem { public string Name { get; set; } public string Birthday { get; set; } }
- 在你的配置工具类中新增绑定配置节点的通用方法
public T GetConfigSection<T>(string sectionName) { // 如果你后续要把节点挪到AppSettings下,就把参数改成 $"AppSettings:{sectionName}" return _configuration.GetSection(sectionName).Get<T>(); }
- 调用读取
// 沿用你原有配置结构的调用方式(不需要改配置) var studentBirthdays = _configHelper.GetConfigSection<List<Dictionary<string, string>>>("StudentBirthdays"); // 用调整后规范结构的调用方式 // var studentBirthdays = _configHelper.GetConfigSection<List<StudentBirthdayItem>>("StudentBirthdays"); // 遍历读取所有学生信息 foreach (var item in studentBirthdays) { // 原有结构的取值逻辑 string name = item.First().Key; string birthday = item.First().Value; // 规范结构的取值逻辑 // string name = item.Name; // string birthday = item.Birthday; // 这里处理你的业务逻辑即可 }
方案2:不修改现有工具类的遍历方案
如果不想改动现有封装逻辑,可以手动按数组索引拼接路径读取:
var studentList = new List<(string Name, string Birthday)>(); int index = 0; while (true) { // 按数组索引拼接配置路径,注意不要加AppSettings前缀 var section = _configuration.GetSection($"StudentBirthdays:{index}"); if (!section.Exists()) break; var child = section.GetChildren().FirstOrDefault(); if (child != null) { studentList.Add((child.Key, child.Value)); } index++; } // 遍历studentList即可获取所有学生的姓名、生日信息
内容的提问来源于stack exchange,提问作者rissa
相关产品推荐
相关产品推荐

