Getting JsonPropertyAttribute Property

I found a post with a great answer to the problem that I have, but I can’t find the small part I'm looking for.

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

I need a method that returns the JsonProperty PropertyName specific property. Perhaps there is something where I can pass the Type and Property I need, and the method returns a value if it is found.

Here is a method that I found that has me in the right direction (I believe) 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)); } 

The goal is to call such a function (any modification is ok)

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

Update # 1

I changed the above, but I do not know how to get the ID string from 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 want to prevent hard-coding strings of actual property names. For example, I do not want to call the above method as:

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

I would rather use something like

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

But I'm not quite sure how to do it right.

Thanks!

+1
source share
1 answer

Here is a way to do this, while preserving strictly written:

 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; } 

And name it as follows:

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

You can make this more general, for example:

 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>(); } 

And now, since the attribute is generic, you need to move the PropertyName call outside:

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

Source: https://habr.com/ru/post/1235569/


All Articles