.NET Core中的强类型配置将忽略JsonProperty属性 [英] Strongly-Typed Configuration in .NET Core ignores JsonProperty attribute

查看:605
本文介绍了.NET Core中的强类型配置将忽略JsonProperty属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用.NET Core中的强类型配置,并且发现了一些奇怪行为.

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"
      }
    ]
  }
}

当我加载配置时:

var builder = new ConfigurationBuilder().AddJsonFile(path);
var config = builder.Build().GetSection("moduleConfiguration").Get<T>();

MenuItems 集合为空,但是如果我将"menu"更改为"menuItems"(在settings.json中),则该集合会正确填充.

the MenuItems collection is null, but if I change "menu" to "menuItems" (in settings.json), the collection is populated correctly.

这是否意味着 JsonProperty 属性被忽略了?

Does it mean that JsonProperty attribute is being ignored?

谢谢

推荐答案

Microsoft.Extensions.Configuration(尤其是Microsoft.Extensions.Configuration.Json)的工作方式不是这样.由于配置设置可以来自不同的来源,例如xml文件,环境变量或命令行参数,因此它不使用JSON.NET来反序列化配置.

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.

例如,如果要通过配置访问moduleConfiguration.menu,则必须执行Configuration["moduleConfiguration:menu"](请注意,冒号:用作子对象的分隔符).

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

由于上述原因,通过[JsonProperty("menu")]注释属性不会执行任何操作,因为JSON.NET不参与此过程,并且Attributes只是元数据,并且它们本身不会执行任何操作.

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.

这就是说:C#中的属性和json中的属性(或xml或命令行参数)必须精确(不区分大小写).

That being said: the property in C# and the properties in json (or xml or commandline parameters) must exactly (case insensitive).

这篇关于.NET Core中的强类型配置将忽略JsonProperty属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆