0

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.

2
  • 2
    You need to do pretty much the same you're doing for "DevicePool": see this answer Commented Oct 19, 2020 at 16:57
  • I see, it seems people were doing that but with a extension library. Thanks for pointing it out. Commented Oct 19, 2020 at 20:44

1 Answer 1

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>>();
Sign up to request clarification or add additional context in comments.

1 Comment

I'm not the OP but I struggled with this and in the end just made a new JSON file, and returned it as a string. In my case I didn't have a need to deserialize just sending to a front end as a configuration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.