In my appSettings.json, I have a configuration section that can contain anything as long as it's json valid. It is usally a set of key/value (string/string)
I would like to get it in my code and return it in a controller call.
I took a look at the source code (https://github.com/aspnet/Configuration/blob/6d9519622b5db2c5ac6bafa8bcdb25fe27914de3/src/Config.Binder/ConfigurationBinder.cs ) and it seems I am doomed with off-the-shelves solutions.
If I limit the use case to key value pairs, I can use the AsEnumerable() in the IConfigSection and that's fine. If I want to allow lists, then I may still be ok parsing the keys to look for :Number but does someone has a way to easily deserialize a random object ? Or even better get the configuration section as is without deserializing it.
For example
{
"mySettings":
{
"key1": "value1",
"key2": "value2",
"list": [ "item1", "item2", "item3" ],
"complexObject": {
"key": "value",
"anything" : [{"id": "3", "name": "John"}]
}
}
}
It's possible if you abuse .NET 4 dynamic objects. As you said, you can enumerate over all keys in the config, and they all follow the same pattern. With your example, all the keys of interest are:
From this, we can build an
ExpandoObject
, like so:Note: since the colon
:
is used as separator, you can't have a key that contains a colon.Finally, because you now have a dynamic object, you can directly get its properties: