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!