gpt4 book ai didi

c# - Asp.Net Core 从 appsettings.json 获取 json 数组

转载 作者:太空宇宙 更新时间:2023-11-03 12:03:46 27 4
gpt4 key购买 nike

我在获取 appsettings.json 中设置的 json 数组时遇到了问题。

使用Configuration.GetSection("xxx").GetChildren()获取json数组时,返回值为null。然后我用下面的方法解决了这个问题,成功了。

在 appsettings.json 中:

{
"EndPointConfiguration": [
{
"UserName": "TestUser",
"Email": "Test@global.com"
},
{
"UserName": "TestUser",
"Email": "Test@global.com"
}
]
}

然后我创建类:

public class EndPointConfiguration 
{
public string UserName { get; set; }
public string Email { get; set; }
}

最后,使用 EndPointConfiguration 类的数组将起作用:

var endPointConfiguration = Configuration.GetSection("EndPointConfiguration").Get<EndPointConfiguration[]>();

我是 .net 核心的新手,不知道为什么 Configuration.GetSection().GetChildren() 不能工作。有没有高手帮忙解答一下?谢谢。

最佳答案

GetChildren()方法将返回给你 IEnumerable<IConfigurationSection> ,这在处理字符串列表等简单类型时非常有用。例如:

{
"EndPointUsernames": [
"TestUser1",
"TestUser2",
"TestUser3",
"TestUser4"
]
}

可以很容易地添加到字符串数组中,而无需定义单独的类,例如 EndPointConfiguration就像你一样。从这里你可以简单地调用

string[] userNames = Configuration.GetSection("EndPointUsernames").GetChildren().ToArray().Select(c => c.Value).ToArray();

检索这些值。您已经在您的示例中正确地完成了它,因为您已将结果强类型化到 EndPointConfiguration 的列表中。对象。

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

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