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

Nov*_*Dev 4 c# .net-core asp.net-core

这种特殊的设置仍然让我困惑。我使用的是 .NET Core 6,所以所有设置的东西都消失了。我留下了下面的代码(我认为)。我有一个 json 对象数组。我看到人们说这是一本字典,所以我尝试过这个,但是数组中的值没有填充。

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

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

应用程序设置.json:

"TimeSlotMenuIds": [
   {
      "FounderWallEvening": 900000000001136943
   },
   {
      "BravoClubEvening": 900000000001136975
   }
]
Run Code Online (Sandbox Code Playgroud)

我的映射类:

 public class TimeSlotMenuIds 
 {
    public Dictionary<string, long> TimeSlotMenuId { get; set; }
 }
Run Code Online (Sandbox Code Playgroud)

不填充我的 json 文件中的值的东西:

 var test = _configuration.GetSection("TimeSlotMenuIds").Get<TimeSlotMenuIds[]>();
 var t2 = _configuration.GetSection("TimeSlotMenuIds").GetChildren();
    
Run Code Online (Sandbox Code Playgroud)

Dav*_*idG 5

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

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

尽管我认为这是一个令人讨厌的黑客行为。相反,您应该将 JSON 修复为如下所示:

"TimeSlotMenuIds": {
  "FounderWallEvening": 900000000001136943,
  "BravoClubEvening": 900000000001136975
}
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

var test = Configuration.GetSection("TimeSlotMenuIds").Get<Dictionary<string, long>>();
Run Code Online (Sandbox Code Playgroud)