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

.NET Core控制台程序反序列化appsettings.json数组为C# List报错求助

解决.NET Core中appsettings.json反序列化为C# List的问题

你当前的错误根源是错误地将IConfiguration对象序列化为JToken再反序列化——IConfiguration的内部结构和原始JSON并不一致,导致Newtonsoft.Json无法正确解析为你定义的Root类。以下是几种直接可行的解决方案:

方案1:直接使用IConfiguration的绑定功能(推荐)

.NET Core配置系统原生支持将配置绑定到自定义对象,无需手动处理序列化/反序列化:

首先调整类定义(避免和.NET内置Program类重名,减少混淆):

public class ProgramConfig
{
    public string Name { get; set; }
    public string LoggingPath { get; set; }
    public List<string> Emails { get; set; }
}

public class RootConfig
{
    public List<ProgramConfig> Programs { get; set; }
}

然后在Main方法中直接完成绑定:

public static void Main(string[] args)
{
    var configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .Build();

    var rootConfig = new RootConfig();
    configuration.Bind(rootConfig);

    // 遍历Programs进行后续操作
    foreach (var program in rootConfig.Programs)
    {
        Console.WriteLine($"程序名: {program.Name}, 日志路径: {program.LoggingPath}");
    }
}

方案2:直接读取JSON文件内容反序列化

如果必须使用Newtonsoft.Json,跳过IConfiguration序列化步骤,直接读取原始JSON文件内容:

public static void Main(string[] args)
{
    var jsonFilePath = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");
    var jsonContent = File.ReadAllText(jsonFilePath);

    var rootConfig = JsonConvert.DeserializeObject<RootConfig>(jsonContent);

    // 遍历逻辑示例
    foreach (var program in rootConfig.Programs)
    {
        Console.WriteLine($"程序名: {program.Name}, 日志路径: {program.LoggingPath}");
    }
}

针对第二种JSON结构(Programs为键值对对象)的处理

如果你要使用这种结构的JSON:

{
    "Programs": {
        "program 1": {
            "LoggingPath": "test",
            "Emails": [
                "person1@company.com",
                "person2@company.com",
                "person3@company.com"
            ]
        },
        "program 2": {
            "LoggingPath": "test",
            "Emails": [
                "person1@company.com",
                "person2@company.com",
                "person3@company.com"
            ]
        }
    }
}

需要将RootConfig中的Programs改为字典类型:

public class ProgramConfig
{
    public string LoggingPath { get; set; }
    public List<string> Emails { get; set; }
}

public class RootConfig
{
    public Dictionary<string, ProgramConfig> Programs { get; set; }
}

之后用方案1或方案2的方式绑定/反序列化,遍历方式如下:

foreach (var kvp in rootConfig.Programs)
{
    Console.WriteLine($"程序名: {kvp.Key}, 日志路径: {kvp.Value.LoggingPath}");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 09:50:37