Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get Field name with JsonProperty Value

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading