I’m trying to read some objects from appsettings.json. The json contains this structure:
...
"DevicePool": [
{ "device":"185.215.0.91:9082", "phonePair":["644004268", "644049008"],"enabled": "true" },
{ "device":"185.215.0.92:9083", "phonePair":["644491698", "644935005"],"enabled": "true" }
]
...
And I try to read it like this:
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});
}
}
This works, mostly. I can’t get the phonePair part. Device gets its value, enabled too but phonePair is null. I have seen other people using this way to read a list of strings from appsettings. So, don’t know what could be the reason.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Is this works for you? I created a class to serialize, If we know the model data
public class DevicePool
{
public string device { get; set; }
public List<string> phonePair { get; set; } = new List<string>();
public bool enabled { get; set; }
}
Then read it like below
var devicePools= _configuration.GetSection("DevicePool").Get<List<DevicePool>>();
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0