无法在 asp dotnet 3.1 中读取 appsettings.json 形式的字符串数组

Imposible to read array of strings form appsettings.json in asp dot net 3.1

我正在尝试从 appsettings.json 中读取一些对象。 json 包含此结构:

  ...
  "DevicePool": [
    { "device":"185.215.0.91:9082", "phonePair":["644004268", "644049008"],"enabled": "true" },
    { "device":"185.215.0.92:9083", "phonePair":["644491698", "644935005"],"enabled": "true" }    
  ]
  ...

我试着这样读:

public DevicePoolMgr(IConfiguration configuration, string devicePoolConfigKey)
{
    _devices = new List<DevicePoolItem>();
    _configuration = configuration;
    string adbPath = Startup.AppConfig["AppConstants:AdbPath"];
            
    var valuesSection = _configuration.GetSection(devicePoolConfigKey);
    foreach (IConfigurationSection section in valuesSection.GetChildren())
    {
         bool enabled = section.GetValue<bool>("enabled");
         if (!enabled) continue;
                
         string device = section.GetValue<string>("device");
         var phoneNumbers = section.GetValue<string[]>("phonePair");
         DevicePhonePair phonePair = new DevicePhonePair(phoneNumbers[0], phoneNumbers[1]);
                
         _devices.Add(new DevicePoolItem() {Device = device, PhonePair = phonePair, Enabled = enabled});
    }
}

这主要是有效的。我无法获得 phonePair 部分。设备获取其值,也启用但 phonePair 为空。我见过其他人使用这种方式从 appsettings 中读取字符串列表。所以,不知道是什么原因。

这适合你吗?我创建了一个class来序列化,如果我们知道模型数据

public class DevicePool
{
    public string device { get; set; }
    public List<string> phonePair { get; set; } = new List<string>();
    public bool enabled { get; set; }
}

然后像下面这样阅读

var devicePools= _configuration.GetSection("DevicePool").Get<List<DevicePool>>();