You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何读取appsettings.json文件中对象数组内的学生姓名和生日

问题根因
  • 现有GetConfigValue方法仅支持读取字符串类型的单值配置,无法直接解析数组/对象结构的配置
  • 方法硬编码了AppSettings:前缀,但你的StudentBirthdays节点直接位于配置根层级,路径不匹配导致读取失败
实现方案

方案1:扩展工具类做强类型绑定(推荐)

这种方式代码可维护性更高,适合配置结构固定的场景

  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; }
}
  1. 在你的配置工具类中新增绑定配置节点的通用方法
public T GetConfigSection<T>(string sectionName)
{
    // 如果你后续要把节点挪到AppSettings下,就把参数改成 $"AppSettings:{sectionName}"
    return _configuration.GetSection(sectionName).Get<T>();
}
  1. 调用读取
// 沿用你原有配置结构的调用方式(不需要改配置)
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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 21:45:02