.NET Core 6,选项模式,如何从 appsettings 获取 json 对象数组
.NET Core 6, Options Pattern, how to get array of json objects from appsettings
这个特殊的设置仍然让我困惑。我在 .NET Core 6 上,所以所有的设置都没有了。我只剩下下面的代码(我认为)。我有一个 json 对象数组。我看到有人说这是一本字典,所以我试过了,但数组中的值没有填充。
我能够获得更简单的对象来填充它们的值。我也根据其他 SO 帖子尝试过这种模式,但没有成功。
我一直靠近,但没有雪茄 - 我做错了什么?
Appsettings.json:
"TimeSlotMenuIds": [
{
"FounderWallEvening": 900000000001136943
},
{
"BravoClubEvening": 900000000001136975
}
]
我的映射class:
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));
虽然我认为这是一个令人讨厌的黑客攻击。相反,您应该将 JSON 修改为如下内容:
"TimeSlotMenuIds": {
"FounderWallEvening": 900000000001136943,
"BravoClubEvening": 900000000001136975
}
这将允许您这样做:
var test = Configuration.GetSection("TimeSlotMenuIds").Get<Dictionary<string, long>>();
这个特殊的设置仍然让我困惑。我在 .NET Core 6 上,所以所有的设置都没有了。我只剩下下面的代码(我认为)。我有一个 json 对象数组。我看到有人说这是一本字典,所以我试过了,但数组中的值没有填充。
我能够获得更简单的对象来填充它们的值。我也根据其他 SO 帖子尝试过这种模式,但没有成功。
我一直靠近,但没有雪茄 - 我做错了什么?
Appsettings.json:
"TimeSlotMenuIds": [
{
"FounderWallEvening": 900000000001136943
},
{
"BravoClubEvening": 900000000001136975
}
]
我的映射class:
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));
虽然我认为这是一个令人讨厌的黑客攻击。相反,您应该将 JSON 修改为如下内容:
"TimeSlotMenuIds": {
"FounderWallEvening": 900000000001136943,
"BravoClubEvening": 900000000001136975
}
这将允许您这样做:
var test = Configuration.GetSection("TimeSlotMenuIds").Get<Dictionary<string, long>>();