代码之家  ›  专栏  ›  技术社区  ›  RoLYroLLs

获取属性的JsonPropertyAttribute

  •  5
  • RoLYroLLs  · 技术社区  · 8 年前

    public class myModel
    {
       [JsonProperty(PropertyName = "id")]
       public long ID { get; set; }
       [JsonProperty(PropertyName = "some_string")]
       public string SomeString {get; set;} 
    }
    

    我需要一个返回 JsonProperty PropertyName 指特定财产。也许是我可以通过的地方 Type Property 我需要,如果找到,该方法将返回值。

    taken from here

    using System.Linq;
    using System.Reflection;
    using Newtonsoft.Json;
    ...
    
    public static string GetFields(Type modelType)
    {
        return string.Join(",",
            modelType.GetProperties()
                     .Select(p => p.GetCustomAttribute<JsonPropertyAttribute>()
                     .Where(jp => jp != null)
                     .Select(jp => jp.PropertyName));
    }
    

    目标是调用这样的函数(任何修改都可以)

    string field = GetField(myModel, myModel.ID);
    

    我修改了上面的内容,但我不知道如何获取 ID 从…起 myModel.ID .

    public static string GetFields(Type modelType, string field) {
        return string.Join(",",
            modelType.GetProperties()
                .Where(p => p.Name == field)
                .Select(p => p.GetCustomAttribute<JsonPropertyAttribute>())
                .Where(jp => jp != null)
                .Select(jp => jp.PropertyName)
            );
    }
    

    实际属性名称的硬编码字符串。例如I 要将上述方法调用为:

    string field = GetField(myModel, "ID");
    

    string field = GetField(myModel, myModel.ID.PropertyName);
    

    谢谢

    1 回复  |  直到 8 年前
        1
  •  8
  •   DavidG    8 年前

    这里有一种方法可以在保持事物强类型的同时做到这一点:

    public static string GetPropertyAttribute<TType>(Expression<Func<TType, object>> property)
    {
        var memberExpression = property.Body as MemberExpression;
        if(memberExpression == null)
            throw new ArgumentException("Expression must be a property");
    
        return memberExpression.Member
            .GetCustomAttribute<JsonPropertyAttribute>()
            .PropertyName;
    }
    

    var result = GetPropertyAttribute<myModel>(t => t.SomeString);
    

    您可以使其更通用一些,例如:

    public static TAttribute GetPropertyAttribute<TType, TAttribute>(Expression<Func<TType, object>> property)
    where TAttribute : Attribute
    {
        var memberExpression = property.Body as MemberExpression;
        if(memberExpression == null)
            throw new ArgumentException("Expression must be a property");
    
        return memberExpression.Member
            .GetCustomAttribute<TAttribute>();
    }
    

    现在因为属性是泛型的,所以需要移动 PropertyName

    var attribute = GetPropertyAttribute<myModel, JsonPropertyAttribute>(t => t.SomeString);
    var result = attribute.PropertyName;