gpt4 book ai didi

c# - .NET Core 6,选项模式,如何从 appsettings 获取 json 对象数组

转载 作者:行者123 更新时间:2023-12-05 01:51:19 24 4
gpt4 key购买 nike

这个特殊的设置一直让我困惑。我在 .NET Core 6 上,所以所有的设置都没有了。我只剩下下面的代码(我认为)。我有一个 json 对象数组。我看到有人说这是一本字典,所以我试过了,但数组中的值没有填充。

我能够得到更简单的对象来填充它们的值。我也根据其他 SO 帖子尝试过这种模式,但没有成功。

我一直靠近,但没有雪茄 - 我做错了什么?

Appsettings.json:

"TimeSlotMenuIds": [
{
"FounderWallEvening": 900000000001136943
},
{
"BravoClubEvening": 900000000001136975
}
]

我的映射类:

 public class TimeSlotMenuIds 
{
public Dictionary<string, long> TimeSlotMenuId { get; set; }
}

没有从我的 json 文件中填充值的东西:

 var test = _configuration.GetSection("TimeSlotMenuIds").Get<TimeSlotMenuIds[]>();
var t2 = _configuration.GetSection("TimeSlotMenuIds").GetChildren();

最佳答案

您的 JSON 结构并不真正适合直接反序列化为字典,而是可以用作字典数组,例如Dictionary<string, long>[] .我确定您不希望这样,因此可以选择手动处理配置:

var test = Configuration.GetSection("TimeSlotMenuIds")
.GetChildren()
.ToDictionary(
x => x.GetChildren().First().Key,
x => long.Parse(x.GetChildren().First().Value));

虽然我认为这是一个令人讨厌的 hack。相反,您应该将 JSON 修复为如下所示:

"TimeSlotMenuIds": {
"FounderWallEvening": 900000000001136943,
"BravoClubEvening": 900000000001136975
}

这将允许您这样做:

var test = Configuration.GetSection("TimeSlotMenuIds").Get<Dictionary<string, long>>();

关于c# - .NET Core 6,选项模式,如何从 appsettings 获取 json 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72339070/

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