作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这个特殊的设置一直让我困惑。我在 .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/
我是一名优秀的程序员,十分优秀!