3

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?

1
  • Where is the attribute JsonProperty defined? Commented Mar 29, 2017 at 18:00

1 Answer 1

6

That's not how Microsoft.Extensions.Configuration (and Microsoft.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 do Configuration["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).

Sign up to request clarification or add additional context in comments.

Comments

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.