【问题标题】:Get value of a class property by JsonProperty通过 JsonProperty 获取类属性的值
【发布时间】:2020-04-07 21:16:03
【问题描述】:

对于环境设置,我们将 JSON blob 存储在我们的数据库中,例如:

[
  {
    "env": "local",
    "keya": "valueA_local"
    "keyb": "valueB_local"
  },
  {
    "env": "development",
    "keya": "valueA_dev"
    "keyb": "valueB_dev"
  },
  {
    "env": "qa",
    "keya": "valueA_qa"
    "keyb": "valueB_qa"
  }
]

我们有一个枚举:

public enum EnvironmentSettings
{
    KeyA = 1,
    KeyB = 2,
}

我们有一个类:

[Serializable]
public class MyProjectEnvironmentSettings
{
    [JsonProperty("env")]
    public string Environment { get; set; }

    [JsonProperty("keya")]
    public string KeyA{ get; set; }

    [JsonProperty("keyb")]
    public string KeyB{ get; set; }
}

最后,我需要创建一个返回给定对的值的方法。如果添加了新设置,我希望不必修改此方法。

public string GetEnvironmentSetting(EnvironmentSettings environmentSetting)
{
    List<MyProjectEnvironmentSettings> environmentSettings = //  get the entire list from the DB
    string envName = // get environment
    string keyToGet = environmentSetting.ToString().ToLower();

    // This will get the group of settings specific to the environment
    var envSettings = environmentSettings.Where(e => e.Environment.ToLower() == envName).FirstOrDefault();

    // And last, I need to get the value for the specific setting that is being requested 
    string settingValue = envSettings.Where(e => e.???? == keyToGet );  // <---------- This is where I need help!
}

我不确定如何通过属性JsonProperty 属性进行查询。

谢谢!

【问题讨论】:

    标签: c# json linq


    【解决方案1】:

    你可以使用反射。

    var property = typeof(MyProjectEnvironmentSettings)
        .GetProperties()
        .FirstOrDefault(prop => prop
            .GetCustomAttribute<JsonPropertyAttribute>()?.PropertyName == keyToGet);
    string settingValue = property?.GetValue(envSettings);
    

    如果您更改属性的可访问性,您可能需要添加 BindingFlags


    这样您就不必更改 GetEnvironmentSetting 方法,但每次添加内容时仍需要更新枚举和类的属性。

    此外,您仍然需要确保名称匹配。您还可以在枚举和属性之间创建映射(甚至直接到 PropertyInfo,因此您可以缓存它们),但这会创建您必须为每次更改维护的第三件事。

    【讨论】:

    • 我怀疑 OP 是在询问“如何通过自定义属性的值查找属性”,而不仅仅是“如何通过名称获取属性”——类似于 stackoverflow.com/questions/3289198/… 而不是 stackoverflow.com/questions/5508050/…跨度>
    • 谢谢!测试。
    • @GetCustomAttribute&lt;JsonProperty&gt;我收到The type 'System.Text.Json.JsonProperty' cannot be used as type parameter 'T' in the generic type or method 'CustomAttributeExtensions.GetCustomAttribute&lt;T&gt;(MemberInfo)'. There is no boxing conversion from 'System.Text.Json.JsonProperty' to 'System.Attribute'.
    • 是的,应该是JsonPropertyAttibute。由于我是从记忆中输入的,因此可能存在一些语法错误。我在答案中修复了它@CaseyCrookston
    猜你喜欢
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    • 2011-12-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-25
    • 2012-11-17
    • 1970-01-01
    相关资源
    最近更新 更多