I've been playing with strongly-typed configuration in .NET Core and I've found some weird behavior.
POCO
public class ModuleConfiguration
{
[JsonProperty("menu")]
public List<MenuItem> MenuItems { get; set; }
}
Settings.json
{
"moduleConfiguration": {
"menu": [
{
"id": 1,
"name": "test"
}
]
}
}
When I load the configuration:
var builder = new ConfigurationBuilder().AddJsonFile(path);
var config = builder.Build().GetSection("moduleConfiguration").Get<T>();
the MenuItems collection is null, but if I change "menu" to "menuItems" (in settings.json), the collection is populated correctly.
Does it mean that JsonProperty attribute is being ignored?
Thanks
That's not how
Microsoft.Extensions.Configuration
(andMicrosoft.Extensions.Configuration.Json
in particular) works. It doesn't use JSON.NET to deserialize the configuration due to the fact that configuration settings can come from different sources, for example xml files, environment variable or command line parameters.All of these are stored in a dictionary and queried.
For example if you want to access
moduleConfiguration.menu
via configuration you have to doConfiguration["moduleConfiguration:menu"]
(note that colon:
is used as separator for child objects).For the reasons named above, annotating the property via
[JsonProperty("menu")]
won't do anything, because JSON.NET isn't involved in the process and the Attributes are just meta data and do not do anything by themselves.Also when you observe the source code on GitHub, you will see that it uses the
JsonReader
and a visitor pattern to populate the dictionary.That being said: the property in C# and the properties in json (or xml or commandline parameters) must exactly (case insensitive).