如何从appsettings中获取一个JSON对象数组:.NET Core 6,Options Pattern

4
这个特定的设置一直困扰着我。我使用的是.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();
    

“_configuration” 适用于哪里? - Luuk
1个回答

5
你的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>>();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接