i have a class defines a field like this
[JsonProperty("json_field")] // <-- this is my input: json_field
public string JsonField { get; set; } // <-- this is my output: JsonField
people usually want to get "json_field" string when they know "JsonField" string, for EG: Get the name of JsonProperty Attribute using reflection c#
but my goal is the opposite. I want to get the string "JsonField" with my input is "json_field"
Is there any solution
private string GetFieldNameFromJsonPropertyAttribute(string json_field)
{
// implement here
return JsonField;
}
>Solution :
You can use reflection. Here’s an implementation of the GetFieldNameFromJsonPropertyAttribute method:
public string GetFieldNameFromJsonPropertyAttribute(string jsonProperty)
{
// Get the class type
Type classType = typeof(YourClass);
// Get all properties of the class
var properties = classType.GetProperties();
// Iterate through the properties to find the matching JsonPropertyAttribute
foreach (var property in properties)
{
var jsonPropertyAttribute = property.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonPropertyAttribute != null && jsonPropertyAttribute.PropertyName == jsonProperty)
{
return property.Name;
}
}
return null;
}
This method retrieves the class type, gets all its properties, and iterates through them to find the property with the matching JsonPropertyAttribute and PropertyName. If found, it returns the property name.
This assumes that you have a class with properties decorated with JsonPropertyAttribute. If your class structure is different, you might need to adjust it accordingly.