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

如何在.NET Core中读取appsettings.json中的嵌套对象?

解决.NET Core读取appsettings.json配置转换为CellDetails列表的问题

你的原代码无法工作,是因为ServiceDetails:CellDetails是一个包含多个键值对的配置对象,而非字符串数组,Get<string[]>()无法匹配这种结构。以下是正确的实现方式:

步骤1:读取目标配置节

先获取CellDetails对应的配置节点:

var cellDetailsSection = configuration.GetSection("ServiceDetails:CellDetails");

步骤2:遍历配置节点并转换为CellDetails列表

遍历CellDetails下的所有子节点,将每个键值对转换为CellDetails对象:

using System.Text.RegularExpressions;
using System.Collections.Generic;

// 初始化列表
var cellDetailsList = new List<CellDetails>();

// 遍历所有子配置项
foreach (var childSection in cellDetailsSection.GetChildren())
{
    // 将驼峰命名的键转为空格分隔的友好名称(如ScenarioName → scenario name)
    var friendlyKeyName = Regex.Replace(childSection.Key, "(?<!^)([A-Z])", " $1").ToLower();
    
    // 读取对应的int数组
    var rowColumnValues = childSection.Get<int[]>();
    
    // 确保数组有两个元素,避免索引越界
    if (rowColumnValues != null && rowColumnValues.Length == 2)
    {
        cellDetailsList.Add(new CellDetails
        {
            CellKeyValue = friendlyKeyName,
            Row = rowColumnValues[0],
            Column = rowColumnValues[1]
        });
    }
}

可选:手动映射键名(避免正则依赖)

如果不想用正则处理键名,可以手动创建映射字典,更可控:

var keyNameMap = new Dictionary<string, string>
{
    { "ScenarioName", "scenario name" },
    { "ServiceName", "service name" }
};

foreach (var childSection in cellDetailsSection.GetChildren())
{
    if (keyNameMap.TryGetValue(childSection.Key, out var friendlyName))
    {
        var rowColumnValues = childSection.Get<int[]>();
        if (rowColumnValues != null && rowColumnValues.Length == 2)
        {
            cellDetailsList.Add(new CellDetails
            {
                CellKeyValue = friendlyName,
                Row = rowColumnValues[0],
                Column = rowColumnValues[1]
            });
        }
    }
}

验证输出

遍历列表即可得到你需要的格式:

foreach (var item in cellDetailsList)
{
    Console.WriteLine($"{item.CellKeyValue}, {item.Row},{item.Column}");
}

输出结果:

scenario name, 4,5
service name, 5,5

内容的提问来源于stack exchange,提问作者Niranjan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 17:12:43