5

I have the following configuration

"Options": {
  "Host": "123",
  "UserName": "test",
  "Password": "test",
  "Files": [
    {
      "Key": "asd",
      "Value": {
        "HostLocation": "asd",
        "RemoteLocation": "asd"
      }
    }
  ]
}

And I'm trying to bind it to the following object

public class Options
{
    public string Host { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public Dictionary<string, FileOptions> Files { get; set; }

    public class FileOptions
    {
        public string HostLocation { get; set; }
        public string RemoteLocation { get; set; }
    }
}

The issue is when I'm trying to bind the the Files to the dictionary. They don't get bound. I get a key generated with the value of 1, and the value FileOptions are generated all with default string value.

This is my configuration mapping.

_serviceCollection.Configure<SftpOptions>(_configuration.GetSection("Options"));

What is wrong and how can I map the setting into the Options class.

phuzi
  • 12,078
  • 3
  • 26
  • 50

1 Answers1

4

They don't get bound. I get a key generated with the value of 1, and the value FileOptions are generated all with default string value.

Which is correct since Files is an array in the shown JSON

  "Files": [
    {
      "Key": "asd",
      "Value": {
        "HostLocation": "asd",
        "RemoteLocation": "asd"
      }
    }
  ]

The JSON would need to look like the following to satisfy the desired object graph

"Options": {
  "Host": "123",
  "UserName": "test",
  "Password": "test",
  "Files": {
      "asd": {
        "HostLocation": "asd",
        "RemoteLocation": "asd"
      },
      "someOtherKey" : {
        "HostLocation": "something",
        "RemoteLocation": "something"
      }
    }
  }
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • It is worth noting for anyone who encounters this answer, that all of the members of your Options class must be Properties. You might think you can use a public field and decorate it with the [JsonInclude] attribute, but that doesn't work in this circumstance! – Loophole Jan 17 '23 at 04:02