Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

json - Strongly-Typed Configuration in .NET Core ignores JsonProperty attribute

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...