简体   繁体   English

将 appSettings.json 对象映射到具有不同 Json 属性名称的类

[英]Map appSettings.json object to class with different Json property names

I am trying to map a JSON object in settings.json to a concrete class that has JSON Property Name matching the JSON object in settings.我正在尝试将settings.json中的 JSON 对象映射到具有与设置中的 JSON 对象匹配的 JSON 属性名称的具体类。

public class GoogleServiceAccount
    {
        [JsonPropertyName("type")]
        public string Type { get; set; }

        [JsonPropertyName("project_id")]
        public string ProjectId { get; set; }

        [JsonPropertyName("private_key_id")]
        public string PrivateKeyId { get; set; }
    }

appSettings.json appSettings.json

"GoogleServiceAccount": {
    "type": "service_account",
    "project_id": "xxxxxx-xxxx",
    "private_key_id": "xxxxxxxxxx"
}

Program.cs程序.cs

builder.Services.Configure<GoogleServiceAccount>(configuration.GetSection("GoogleServiceAccount"));

EmailService.cs电子邮件服务.cs

    public class EmailService
    {
        private readonly GoogleServiceAccount _gmailCredentials;
        public EmailService(IOptions<GoogleServiceAccount> credentials)
        {
            _gmailCredentials = credentials.Value;
        }
    }

Issue: I am getting null values in EmailService class for GoogleServiceAccount问题:我在GoogleServiceAccountEmailService类中得到空值

Solution: Since I am using .NET 6, ConfigurationKeyName instead of JsonPropertyName worked.解决方案:由于我使用的是 .NET 6,因此ConfigurationKeyName而不是JsonPropertyName起作用。

public class GoogleServiceAccount
        {
            [ConfigurationKeyName("type")]
            public string Type { get; set; }
    
            [ConfigurationKeyName("project_id")]
            public string ProjectId { get; set; }
    
            [ConfigurationKeyName("private_key_id")]
            public string PrivateKeyId { get; set; }
        }

Configure like this code in your Program.cs :在您的Program.cs中配置如下代码:

builder.Services.Configure<GoogleServiceAccount>(o=> {
    o.Type = builder.Configuration["GoogleServiceAccount:type"];
    o.ProjectId = builder.Configuration["GoogleServiceAccount:project_id"];
    o.PrivateKeyId = builder.Configuration["GoogleServiceAccount:private_key_id"];

});

Demo演示

在此处输入图像描述 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM