【问题标题】:Strongly-Typed Configuration in .NET Core ignores JsonProperty attribute.NET Core 中的强类型配置忽略 JsonProperty 属性
【发布时间】:2017-08-23 08:29:23
【问题描述】:

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

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 中),则该集合被正确填充。

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

【问题讨论】:

  • 属性JsonProperty在哪里定义的?

标签: json asp.net-core json.net .net-core


【解决方案1】:

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

所有这些都存储在字典中并进行查询。

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

由于上面提到的原因,通过[JsonProperty("menu")] 注释属性不会做任何事情,因为 JSON.NET 不参与该过程,并且属性只是元数据,它们本身不会做任何事情。

当您观察GitHub 上的源代码时,您会看到它使用JsonReader 和访问者模式来填充字典。

话虽如此:C# 中的属性和 json 中的属性(或 xml 或命令行参数)必须完全一致(不区分大小写)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多