gpt4 book ai didi

c# - 从 appsettings c# 读取 json 数组

转载 作者:太空宇宙 更新时间:2023-11-03 20:54:56 25 4
gpt4 key购买 nike

我的 appsettings.json 中有数组

"steps": [
{
"name": "IMPORT",
"enabled": true
},
{
"name": "IMPORT_XML",
"enabled": true
},
{
"name": "COMPARE",
"enabled": true
},
{
"test_name": "COMPARE_TABLE",
"enabled": true
}]

在我的类里面,我尝试使用 IConfigurationRoot _configurationRoot

检索它

我试过:

var procSteps = _configurationRoot.GetSection("steps");
foreach (IConfigurationSection section in procSteps.GetChildren())
{
var key = section.GetValue<string>("test");
var value = section.GetValue<string>("enabled");
}

和:

var procSteps = _configurationRoot.GetSection("ExecutionSteps")
.GetChildren()
.Select(x => x.Value)
.ToArray();

但是他们都没有检索到它的值。有谁知道这是怎么回事以及访问此类数组值的正确方法是什么?

最佳答案

创建一个对象模型来保存值

public class ProcessStep {
public string name { get; set; }
public bool enabled { get; set; }
}

然后使用Get<T> 从节中获取数组

ProcessStep[] procSteps = _configurationRoot
.GetSection("steps")
.Get<ProcessStep[]>();

ASP.NET Core 1.1 and higher can use Get<T>, which works with entire sections. Get<T> can be more convenient than using Bind

引用 Configuration in ASP.NET Core: Bind to an object graph

关于c# - 从 appsettings c# 读取 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51499622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com